Databases (JDBC)
The whole of java.sql is generated (Connection, PreparedStatement, ResultSet, DatabaseMetaData), and a few functions make the common work short.
The whole of java.sql is generated (Connection, PreparedStatement, ResultSet, DatabaseMetaData), and a few functions make the common work short. A driver is a jar: jMaven("com.h2database:h2:2.2.224"), "org.xerial:sqlite-jdbc:3.45.1.0", "org.postgresql:postgresql:42.7.3", "com.mysql:mysql-connector-j:8.3.0".
load "java.ring"
jMaven("com.h2database:h2:2.2.224")
oDb = jSqlConnect("jdbc:h2:mem:demo")
jSqlExec(oDb,"create table t(id int, name varchar(40))",[])
jSqlExec(oDb,"insert into t values (?,?)",[1,"Ring"])
for aRow in jSqlQuery(oDb,"select * from t where id > ?",[0])
? aRow[:name]
next
oDb.close()| Function | Meaning |
|---|---|
jSqlConnect(cUrl), jSqlConnectAs(cUrl,cUser,cPassword) | a java.sql.Connection |
jSqlExec(oDb,cSql,aParams) | INSERT, UPDATE, DELETE, CREATE: the number of rows that changed |
jSqlQuery(oDb,cSql,aParams) | a SELECT: a list of rows; a row is a list of [name, value] pairs, so aRow[:name] works (names in lower case) |
jSqlValue(oDb,cSql,aParams) | the first column of the first row |
jSqlScript(oDb,cScript) | several statements separated by ; |
aParams are the values of the ? marks (integers, doubles, texts, Java objects). A database null is an empty text; numbers are Ring numbers; dates and other types are texts.
Why not DriverManager.getConnection? DriverManager only sees the drivers of the class loader of the caller, and the jars that a Ring program adds are loaded later. jSqlConnect finds the driver itself (ServiceLoader) on the class path of the program. The objects of the driver (the connection, the statements) are wrapped in the Ring class of the widest public interface they implement (Connection, ResultSet), so oDb.prepareStatement(...) works. Methods of java.sql follow the usual rules: oStmt.executeQuery() for the version without a statement text (a PreparedStatement) and oStmt.@executeQuery("select ...") for the others, @next() for ResultSet.next.
t13_jdbc.ring tests the functions with a driver that has no database (tests/data/fakedb.jar).
JavaDatabase: tables and rows without SQL#
JavaDatabase (libraries/javalib/data.ring) describes the tables as data and does the usual work (insert, read by key, update, delete, conditions, aggregates, relations, transactions) on any JDBC database. It is the counterpart of RingDatabase of RingDotNet.
load "java.ring"
jMaven("com.h2database:h2:2.2.224")
oDb = new JavaDatabase("jdbc:h2:mem:shop",[
["Customers",[ ["Id","int",1], ["Name","string",0], ["Age","int",0], ["City","string",0] ]]
])
nId = oDb.insert("Customers",[["Name","Ann"],["Age",31],["City","Cairo"]])
aRow = oDb.byKey("Customers",nId)
? jDbValue(aRow,"Name")
for aCustomer in oDb.where("Customers","Age > {0} AND City = {1}",[18,"Cairo"])
? jDbValue(aCustomer,"Name")
next
oDb.update("Customers",nId,[["Age",32]])
oDb.remove("Customers",nId)
oDb.close()The model. [table, [[column, type, isKey, options], ...]]. The types are int, long, double, decimal, string, bool, datetime and bytes. Tables that do not exist are created. A key of type int or long is generated by the database; several keys make a composite key (byKey("Enrollments",[nStudent,nCourse])). The options are required, unique, index, maxlength, default, and references with ondelete (cascade, restrict, setnull, noaction). bool columns hold 1 and 0, datetime columns are texts yyyy-MM-dd HH:mm:ss and bytes columns hex texts. Give [] as the model when the tables exist already. The URL says which database it is: H2, SQLite, PostgreSQL, MySQL and HSQLDB have their own forms of the generated key; the others get standard SQL.
The rows. A row is a list of [name, value] pairs (names in lower case, a null is ""); jDbValue(aRow,"Name") reads a column without caring about the case. A condition is SQL with {0} {1} ... marks. They become real parameters of the statement (a mark can be used twice), so there is no injection. Names of tables and columns have letters, digits and _ only, and are not reserved words of SQL (Year, Order, Group, User ...).
| Method | Meaning |
|---|---|
insert(table, values) | add a row ([[name, value], ...]); gives the key |
byKey(table, key), all(table), where(table, condition, params) | read rows |
update(table, key, values), remove(table, key) | change or delete the row with the key; the number of rows |
count(table), scalar(sql, params), execute(sql, params), sqlRows(sql, params) | totals and any SQL, with {0} marks |
query(table, spec) | a query as data (below) |
aggregate(table, function, column, condition), sum, min, max, average, countWhere | totals of a column for the rows that match a condition ([] = all) |
groupCount(table, column, condition) | [[value, count], ...] |
children(parent, key, childTable), parent(child, key, parentTable) | the rows of a relation made with references |
begin(), commit(), rollback() | a transaction |
tables(), connection(), dialect(), close() | the names of the tables; the java.sql.Connection; the kind of database |
A query as data:
oDb.query("Customers",[
["where",["and",["Age",">",30],["City","in",["Cairo","Giza"]]]],
["orderby",[["Age","desc"]]],
["skip",10],
["take",5],
["select",["Name","Age"]]
])A condition is [column, op, value] with the operators =, !=, <, <=, >, >=, contains, startswith, endswith, in, isnull and notnull, or ["and", c1, c2 ...], ["or", c1, c2 ...] and ["not", c]. The values are parameters; contains and its relatives take % and _ literally. skip and take must be whole numbers (an error otherwise): they are part of the SQL text, not parameters.
Give a java.sql.Connection instead of the URL when the database needs a user and a password: new JavaDatabase(jSqlConnectAs(cUrl,cUser,cPassword),aModel).
t22_data.ring runs the whole model on H2 and on SQLite.