Table creation: Difference between revisions

Content added Content deleted
(added Perl programming solution)
m (syntax highlighting fixup automation)
Line 11: Line 11:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>; Helper functions
<syntaxhighlight lang="rebol">; Helper functions


createTable: function [][
createTable: function [][
Line 49: Line 49:
print ["getting user with name: JohnDoe =>" findUser "JohnDoe"]
print ["getting user with name: JohnDoe =>" findUser "JohnDoe"]


close db</lang>
close db</syntaxhighlight>


{{out}}
{{out}}
Line 62: Line 62:


AWK is just a glue language. Simply pipe the creation command into SQLite and capture the output.
AWK is just a glue language. Simply pipe the creation command into SQLite and capture the output.
<lang awk>#!/bin/sh -f
<syntaxhighlight lang="awk">#!/bin/sh -f
awk '
awk '
BEGIN {
BEGIN {
Line 69: Line 69:
exit;
exit;
}
}
'</lang>
'</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
Line 75: Line 75:


{{libheader|SQLite}}
{{libheader|SQLite}}
<syntaxhighlight lang="c">
<lang C>
#include <sqlite3.h>
#include <sqlite3.h>
#include <stdlib.h>
#include <stdlib.h>
Line 103: Line 103:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>import db.*
<syntaxhighlight lang="funl">import db.*
import util.*
import util.*


Line 132: Line 132:
statement.execute( "SELECT * FROM Persons ORDER BY LastName" )
statement.execute( "SELECT * FROM Persons ORDER BY LastName" )
print( TextTable.apply(statement.getResultSet()) )
print( TextTable.apply(statement.getResultSet()) )
conn.close()</lang>
conn.close()</syntaxhighlight>
{{out}}
{{out}}
Line 152: Line 152:
<br>
<br>
This uses a key/value store rather than a relational database to create the table.
This uses a key/value store rather than a relational database to create the table.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 241: Line 241:
return nil
return nil
})
})
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 257: Line 257:
If we define a <code>table</code> as a named collection of columns, and we define a <code>type</code> as a mechanism for the representation of some kind of data, then:
If we define a <code>table</code> as a named collection of columns, and we define a <code>type</code> as a mechanism for the representation of some kind of data, then:


<lang j>stocks=: |: ,: ;:'date trans symbol qty price'
<syntaxhighlight lang="j">stocks=: |: ,: ;:'date trans symbol qty price'
insertStock=: 3 :'0#stocks=: stocks,.y'
insertStock=: 3 :'0#stocks=: stocks,.y'
insertStock@".;._2]0 :0
insertStock@".;._2]0 :0
Line 264: Line 264:
'2006-04-05'; 'BUY'; 'MSOFT'; 1000; 72.00
'2006-04-05'; 'BUY'; 'MSOFT'; 1000; 72.00
'2006-04-06'; 'SELL'; 'IBM'; 500; 53.00
'2006-04-06'; 'SELL'; 'IBM'; 500; 53.00
)</lang>
)</syntaxhighlight>


declares a table and some data within that table.
declares a table and some data within that table.
Line 270: Line 270:
And, here's an example of sorting:
And, here's an example of sorting:


<lang j>cols=: [:; {."1@[ <@i.`(<@i.@#@[)@.(=&(<,'*')@]"1 0) cutopen@]
<syntaxhighlight lang="j">cols=: [:; {."1@[ <@i.`(<@i.@#@[)@.(=&(<,'*')@]"1 0) cutopen@]
sortBy=: [ /:"1 2 (<__)|:@,. [ }.@{~ cols
sortBy=: [ /:"1 2 (<__)|:@,. [ }.@{~ cols
from=: cols~ {"0 _ ]
from=: cols~ {"0 _ ]
Line 286: Line 286:
├──────────┼─────┼──────┼────┼─────┤
├──────────┼─────┼──────┼────┼─────┤
│2006-04-05│BUY │MSOFT │1000│72 │
│2006-04-05│BUY │MSOFT │1000│72 │
└──────────┴─────┴──────┴────┴─────┘</lang>
└──────────┴─────┴──────┴────┴─────┘</syntaxhighlight>


Note that this particular example is both overly general in some senses (for example, named column handling has features not demonstrated here) and overly specific in others (for example, I did not implement sort in descending order).
Note that this particular example is both overly general in some senses (for example, named column handling has features not demonstrated here) and overly specific in others (for example, I did not implement sort in descending order).
Line 295: Line 295:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>using SQLite
<syntaxhighlight lang="julia">using SQLite


conn = SQLite.DB() # in-memory
conn = SQLite.DB() # in-memory
Line 317: Line 317:


df = SQLite.query(conn, "select * from stocks order by price")
df = SQLite.query(conn, "select * from stocks order by price")
println(df)</lang>
println(df)</syntaxhighlight>


{{out}}
{{out}}
Line 329: Line 329:


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>Columns = {};
<syntaxhighlight lang="lua">Columns = {};
Columns.ID = {};
Columns.ID = {};
Columns.FName = {};
Columns.FName = {};
Line 384: Line 384:
--[[ ]]--
--[[ ]]--


listTables();</lang>
listTables();</syntaxhighlight>


{{out}}
{{out}}
Line 403: Line 403:
We can use text from UTF16LE set. Here we have Greek letters in Memo.
We can use text from UTF16LE set. Here we have Greek letters in Memo.


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
MODULE SIMPLEBASE {
MODULE SIMPLEBASE {
BASE "ALFA" ' ERASED IF FOUND THE NAME OF "ALFA.MDB"
BASE "ALFA" ' ERASED IF FOUND THE NAME OF "ALFA.MDB"
Line 419: Line 419:
}
}
SIMPLEBASE
SIMPLEBASE
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Needs["DatabaseLink`"];conn = OpenSQLConnection[JDBC["mysql",
<syntaxhighlight lang="mathematica">Needs["DatabaseLink`"];conn = OpenSQLConnection[JDBC["mysql",
"databases:1234/conn_test"], "Username" -> "test"]
"databases:1234/conn_test"], "Username" -> "test"]
SQLCreateTable[conn, SQLTable["TEST"],If[Length[#] == 0,SQLColumn[StringJoin[#,"COL"],"DataTypeName" -> #],SQLColumn[StringJoin[#[[1]], "COL"], "DataTypeName" -> #[[1]],"DataLength" -> #[[2]]]] & /@ {"TINYINT", "SMALLINT", "INTEGER","BIGINT", "NUMERIC", "DECIMAL", "FLOAT", "REAL", "DOUBLE", "BIT","LONGVARBINARY", "VARBINARY", "BINARY","LONGVARCHAR",{"VARCHAR", 5},{"CHAR", 3},"DATE","TIME","TIMESTAMP","OBJECT"}]</lang>
SQLCreateTable[conn, SQLTable["TEST"],If[Length[#] == 0,SQLColumn[StringJoin[#,"COL"],"DataTypeName" -> #],SQLColumn[StringJoin[#[[1]], "COL"], "DataTypeName" -> #[[1]],"DataLength" -> #[[2]]]] & /@ {"TINYINT", "SMALLINT", "INTEGER","BIGINT", "NUMERIC", "DECIMAL", "FLOAT", "REAL", "DOUBLE", "BIT","LONGVARBINARY", "VARBINARY", "BINARY","LONGVARCHAR",{"VARCHAR", 5},{"CHAR", 3},"DATE","TIME","TIMESTAMP","OBJECT"}]</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
Line 430: Line 430:
Nim standard library provides two modules to work with SQL databases. We use here the high level one for SQLite.
Nim standard library provides two modules to work with SQL databases. We use here the high level one for SQLite.


<lang Nim>import db_sqlite
<syntaxhighlight lang="nim">import db_sqlite


let dbc = open(":memory:", "", "", "")
let dbc = open(":memory:", "", "", "")
Line 445: Line 445:
# Data retrieval.
# Data retrieval.
for row in dbc.fastRows(sql"select * from stocks order by price"):
for row in dbc.fastRows(sql"select * from stocks order by price"):
echo row</lang>
echo row</syntaxhighlight>


{{out}}
{{out}}
Line 455: Line 455:
=={{header|Oracle}}==
=={{header|Oracle}}==
Great SCOTT! from utlsampl.sql
Great SCOTT! from utlsampl.sql
<lang sql>
<syntaxhighlight lang="sql">
CREATE TABLE EMP
CREATE TABLE EMP
(EMPNO NUMBER(4) CONSTRAINT PK_EMP PRIMARY KEY,
(EMPNO NUMBER(4) CONSTRAINT PK_EMP PRIMARY KEY,
Line 465: Line 465:
COMM NUMBER(7,2),
COMM NUMBER(7,2),
DEPTNO NUMBER(2) CONSTRAINT FK_DEPTNO REFERENCES DEPT);
DEPTNO NUMBER(2) CONSTRAINT FK_DEPTNO REFERENCES DEPT);
</syntaxhighlight>
</lang>


=={{header|Oz}}==
=={{header|Oz}}==
Line 473: Line 473:
{{libheader|Ozsqlite}}
{{libheader|Ozsqlite}}


<lang oz>declare
<syntaxhighlight lang="oz">declare
[Sqlite] = {Module.link ['x-ozlib:/sqlite/Sqlite.ozf']}
[Sqlite] = {Module.link ['x-ozlib:/sqlite/Sqlite.ozf']}


Line 510: Line 510:
{Sqlite.close DB}
{Sqlite.close DB}
end
end
</syntaxhighlight>
</lang>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
The most natural way to store tabular data in GP is in a matrix:
The most natural way to store tabular data in GP is in a matrix:
<lang parigp>m=matrix(10,3);
<syntaxhighlight lang="parigp">m=matrix(10,3);
m[1,] = ["Barack", "Obama", 20500];
m[1,] = ["Barack", "Obama", 20500];
\\ ...</lang>
\\ ...</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
{{trans|Julia}}
{{trans|Julia}}
<lang perl># 20211218 Perl programming solution
<syntaxhighlight lang="perl"># 20211218 Perl programming solution


use strict;
use strict;
Line 552: Line 552:
print '=' x 75 , "\n";
print '=' x 75 , "\n";


while ( my @row = $sth->fetchrow_array ) { printf $format, @row }</lang>
while ( my @row = $sth->fetchrow_array ) { printf $format, @row }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 565: Line 565:
=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|SQLite}}
{{libheader|SQLite}}
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">include</span> <span style="color: #000000;">pSQLite</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pSQLite</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">sqlcode</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
<span style="color: #008080;">constant</span> <span style="color: #000000;">sqlcode</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
Line 582: Line 582:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"sqlite3_exec error: %d [%s]\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sqlite_last_exec_err</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"sqlite3_exec error: %d [%s]\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sqlite_last_exec_err</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(scl 2)
<syntaxhighlight lang="picolisp">(scl 2)


(class +Account +Entity)
(class +Account +Entity)
Line 619: Line 619:
(if (: active) "Yes" "No")
(if (: active) "Yes" "No")
(: username)
(: username)
(money (: balance)) ) ) )</lang>
(money (: balance)) ) ) )</syntaxhighlight>
Output:
Output:
<pre>account_id created active username balance
<pre>account_id created active username balance
Line 626: Line 626:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>declare 1 table (100),
<syntaxhighlight lang="pl/i">declare 1 table (100),
2 name character (20) varying,
2 name character (20) varying,
2 address,
2 address,
Line 635: Line 635:
2 transaction_date date,
2 transaction_date date,
2 sex character (1),
2 sex character (1),
2 suppress_junk_mail bit (1);</lang>
2 suppress_junk_mail bit (1);</syntaxhighlight>


=={{header|PostgreSQL}}==
=={{header|PostgreSQL}}==
Line 641: Line 641:
Postgres developers, please feel free to add additional data-types you commonly use to this example.
Postgres developers, please feel free to add additional data-types you commonly use to this example.


<lang sql>-- This is a comment
<syntaxhighlight lang="sql">-- This is a comment


CREATE SEQUENCE account_seq start 100;
CREATE SEQUENCE account_seq start 100;
Line 668: Line 668:
-- char(#): space padded text field with length of #
-- char(#): space padded text field with length of #
-- varchar(#): variable length text field up to #
-- varchar(#): variable length text field up to #
-- text: not limited</lang>
-- text: not limited</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
{{libheader|SQLite}}
{{libheader|SQLite}}
The sqlite3 database is a part of the Python standard library. It does not associate type with table columns, any cell can be of any type.
The sqlite3 database is a part of the Python standard library. It does not associate type with table columns, any cell can be of any type.
<lang python>>>> import sqlite3
<syntaxhighlight lang="python">>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c = conn.cursor()
Line 707: Line 707:
(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)
(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)
(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)
(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)
>>> </lang>
>>> </syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
This is the relevant part of [[Table creation/Postal addresses#Racket]] that creates the DB table:
This is the relevant part of [[Table creation/Postal addresses#Racket]] that creates the DB table:
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(require db)
(require db)
(define postal (sqlite3-connect #:database "/tmp/postal.db" #:mode 'create))
(define postal (sqlite3-connect #:database "/tmp/postal.db" #:mode 'create))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 753: Line 753:
However, tables (or structures) can be constructed by using stemmed arrays; &nbsp; the index would (should) be
However, tables (or structures) can be constructed by using stemmed arrays; &nbsp; the index would (should) be
<br>a unique identifier, &nbsp; something akin to a SSN &nbsp;(Social Security Number)&nbsp; or something similar.
<br>a unique identifier, &nbsp; something akin to a SSN &nbsp;(Social Security Number)&nbsp; or something similar.
<lang rexx> id = 000112222 /*could be a SSN or some other unique ID (or number).*/
<syntaxhighlight lang="rexx"> id = 000112222 /*could be a SSN or some other unique ID (or number).*/


table.id.!firstname = 'Robert'
table.id.!firstname = 'Robert'
Line 764: Line 764:
table.id.!town = 'Gotham City'
table.id.!town = 'Gotham City'
table.id.!state = 'NY'
table.id.!state = 'NY'
table.id.!zip = '12345-6789'</lang><br><br>
table.id.!zip = '12345-6789'</syntaxhighlight><br><br>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Table creation
# Project : Table creation


Line 806: Line 806:
next
next
sqlite_close(oSQLite)
sqlite_close(oSQLite)
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 839: Line 839:
This code is enough to create a PStore (or open an existing PStore).
This code is enough to create a PStore (or open an existing PStore).


<lang ruby>require 'pstore'
<syntaxhighlight lang="ruby">require 'pstore'
db = PStore.new "filename.pstore"</lang>
db = PStore.new "filename.pstore"</syntaxhighlight>


The example at [[Table creation/Postal addresses#Ruby]] puts Ruby objects into the PStore.
The example at [[Table creation/Postal addresses#Ruby]] puts Ruby objects into the PStore.
Line 847: Line 847:
Run Basic supports all features of SQLite.
Run Basic supports all features of SQLite.
This is a sample of a item master
This is a sample of a item master
<lang runbasic>
<syntaxhighlight lang="runbasic">
#sql execute("
#sql execute("
CREATE TABLE item (
CREATE TABLE item (
Line 886: Line 886:
CREATE UNIQUE INDEX item_descr ON item( descr, itemNum);
CREATE UNIQUE INDEX item_descr ON item( descr, itemNum);
CREATE UNIQUE INDEX item_itemNum ON item(itemNum);"
CREATE UNIQUE INDEX item_itemNum ON item(itemNum);"
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
===using SLICK FRM===
===using SLICK FRM===
<lang Scala>// Use H2Profile to connect to an H2 database
<syntaxhighlight lang="scala">// Use H2Profile to connect to an H2 database
import slick.jdbc.H2Profile.api._
import slick.jdbc.H2Profile.api._


Line 925: Line 925:
// Create the tables, including primary and foreign keys
// Create the tables, including primary and foreign keys
(suppliers.schema ++ coffees.schema).create
(suppliers.schema ++ coffees.schema).create
)}</lang>
)}</syntaxhighlight>


=={{header|SQL PL}}==
=={{header|SQL PL}}==
{{works with|Db2 LUW}}
{{works with|Db2 LUW}}
<lang sql pl>
<syntaxhighlight lang="sql pl">
CREATE TABLE dept (
CREATE TABLE dept (
deptno NUMERIC(2)
deptno NUMERIC(2)
Line 963: Line 963:
INSERT INTO emp VALUES (7902, 'FORD', 'ANALYST', 7566, '1981-12-03', 3000, NULL, 20);
INSERT INTO emp VALUES (7902, 'FORD', 'ANALYST', 7566, '1981-12-03', 3000, NULL, 20);
INSERT INTO emp VALUES (7934, 'MILLER', 'CLERK', 7782, '1982-01-23', 1300, NULL, 10);
INSERT INTO emp VALUES (7934, 'MILLER', 'CLERK', 7782, '1982-01-23', 1300, NULL, 10);
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,063: Line 1,063:
=={{header|Tcl}}==
=={{header|Tcl}}==
Tables, as used in relational databases, seem far away conceptually from Tcl. However, the following code demonstrates how a table (implemented as a list of lists, the first being the header line) can be type-checked and rendered:
Tables, as used in relational databases, seem far away conceptually from Tcl. However, the following code demonstrates how a table (implemented as a list of lists, the first being the header line) can be type-checked and rendered:
<lang Tcl>proc table_update {_tbl row args} {
<syntaxhighlight lang="tcl">proc table_update {_tbl row args} {
upvar $_tbl tbl
upvar $_tbl tbl
set heads [lindex $tbl 0]
set heads [lindex $tbl 0]
Line 1,137: Line 1,137:
balance 0.0 \
balance 0.0 \
created 2009-05-14
created 2009-05-14
puts [table_format $mytbl]</lang>
puts [table_format $mytbl]</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,155: Line 1,155:


In practice, a binary search would be needed to find records quickly by key given that the records are being maintained in sorted order. However, for now we use a sequential search instead.
In practice, a binary search would be needed to find records quickly by key given that the records are being maintained in sorted order. However, for now we use a sequential search instead.
<lang ecmascript>import "/dynamic" for Enum, Tuple
<syntaxhighlight lang="ecmascript">import "/dynamic" for Enum, Tuple
import "/fmt" for Fmt
import "/fmt" for Fmt
import "/sort" for Cmp, Sort
import "/sort" for Cmp, Sort
Line 1,262: Line 1,262:
table.removeRecord(3)
table.removeRecord(3)
System.print("\nThe record with an id of 3 will be deleted, leaving:\n")
System.print("\nThe record with an id of 3 will be deleted, leaving:\n")
table.showRecords()</lang>
table.showRecords()</syntaxhighlight>


{{out}}
{{out}}