Skip to content

JDBC driver

View as Markdown

The CoraDB JDBC driver is a type 4 (pure Java) JDBC driver: it implements the CoraDB broker protocol in Java and needs no native library. It supports the JDBC 4 API (Connection, PreparedStatement, CallableStatement, scrollable and updatable ResultSets, DatabaseMetaData, savepoints, Blob/Clob, DataSource, ConnectionPoolDataSource and XADataSource) and runs on Java 7 or later.

The driver ships with CoraDB in the jdbc directory of the installation:

File Content
$CORADB/jdbc/coradb_jdbc.jar The driver (a copy of, or link to, the versioned jar)
$CORADB/jdbc/JDBC-<build>-coradb.jar The same driver, with the build number in its name
$CORADB/jdbc/JDBC-<build>-coradb-src.jar Sources

Add coradb_jdbc.jar to the application's class path:

java -cp .:$CORADB/jdbc/coradb_jdbc.jar MyApp # Linux / macOS
java -cp .;%CORADB%\jdbc\coradb_jdbc.jar MyApp # Windows

The driver class is coradb.jdbc.driver.CORADBDriver. With JDBC 4 it registers itself; on older code, load it explicitly:

Class.forName("coradb.jdbc.driver.CORADBDriver");

jdbc:coradb:<host>:<port>:<database>:[<user>]:[<password>]:[?<property>=<value>[&<property>=<value> ...]]
  • host: broker host name or IP address; empty means localhost.
  • port: broker port; empty means 33000.
  • database: required.
  • user / password: can be left empty in the URL and passed to DriverManager.getConnection(url, user, password) instead (arguments win over the URL). The default user is public.
  • The colons are mandatory, even for empty fields: jdbc:coradb:localhost:33000:e-commerce:::.
String url = "jdbc:coradb:localhost:33000:e-commerce:::?charSet=utf-8&connectTimeout=10";
try (Connection conn = DriverManager.getConnection(url, "dba", "")) {
System.out.println(conn.getMetaData().getDatabaseProductVersion());
}

Inside a Java stored procedure, jdbc:default:connection: returns the connection of the calling session.

Properties are added after ? in the URL, or passed in the Properties object of DriverManager.getConnection(url, info).

Property Default Description
altHosts — Alternative brokers host:port,host:port, used when the main broker cannot be reached.
loadBalance false Pick the broker at random among the main host and altHosts.
rcTime 600 Seconds after which a connection that failed over tries to return to the main broker.
connectTimeout DriverManager.getLoginTimeout(), else 30 Connect timeout in seconds, for each broker tried.
queryTimeout 0 Server-side time limit for each statement, in seconds (0 = none). Statement.setQueryTimeout() overrides it.
charSet JVM file.encoding Character set used to send and read strings, for example utf-8.
zeroDateTimeBehavior exception How a zero date (0000-00-00) is read: exception, convertToNull or round.
resultWithCORADBTypes yes yes: date-time values are returned as CoraDB subclasses of java.sql.Timestamp (coradb.sql.CORADBTimestamp, which keep extra information such as the time zone); no: as plain java.sql.Timestamp.
useLazyConnection false Connect to the broker only when the first statement runs.
useOldBooleanValue false Return booleans as 1/0 instead of true/false.
oracleStyleEmptyString false Treat empty strings as NULL, as the oracle_style_empty_string parameter does.
useSSL false Connect to a broker with SSL=ON.
clientCacheSize 1 Client-side result cache size in MB (1–1024); used only when the broker's JDBC_CACHE is on.
logOnException false Log statements that raise an exception.
logSlowQueries / slowQueryThresholdMillis false / 60000 Log statements slower than the threshold.
logFile coradb_jdbc.log File for the two logs above.

Example with alternative brokers and a statement time limit:

jdbc:coradb:db1:33000:e-commerce:::?altHosts=db2:33000,db3:33000&rcTime=300&queryTimeout=30
Class Use
coradb.jdbc.driver.CORADBDataSource javax.sql.DataSource, for application servers and frameworks
coradb.jdbc.driver.CORADBConnectionPoolDataSource ConnectionPoolDataSource for pool managers
coradb.jdbc.driver.CORADBXADataSource XADataSource for distributed (XA) transactions

Configure them with setServerName(), setPortNumber(), setDatabaseName(), setUser(), setPassword(), or with setUrl() and a full JDBC URL:

CORADBDataSource ds = new CORADBDataSource();
ds.setUrl("jdbc:coradb:localhost:33000:e-commerce:::?charSet=utf-8");
ds.setUser("dba");
ds.setPassword("");
try (Connection conn = ds.getConnection()) {
// ...
}

The driver also works with general-purpose pools such as HikariCP or Apache DBCP: give them the driver class and the URL.

Always prefer PreparedStatement with ? markers: values are bound on the server and never spliced into the SQL text.

String sql = "SELECT name, unit_price FROM product WHERE unit_price > ? ORDER BY unit_price DESC LIMIT 5";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setBigDecimal(1, new BigDecimal("90"));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.printf("%s %s%n", rs.getString("name"), rs.getBigDecimal("unit_price"));
}
}
}

A graph query is an ordinary SELECT. Columns of a MATCH keep their alias in the label (b.name), so read them by position or give them an alias:

String sql =
"SELECT b.name AS brand, COUNT(cu) AS followers " +
"FROM MATCH (cu:customer)-[:follows]->(b:brand) " +
"GROUP BY b.name ORDER BY followers DESC LIMIT ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, 3);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("brand") + ": " + rs.getInt("followers"));
}
}
}
Nike: 209
Adidas: 132
Puma: 94

Connections start in auto-commit mode. Turn it off to group statements; use savepoints for partial rollbacks:

conn.setAutoCommit(false);
try (PreparedStatement ins = conn.prepareStatement(
"INSERT INTO orders (id, customer_id, order_date, shipping_cost, ship_address) VALUES (?, ?, SYSDATE, ?, ?)");
PreparedStatement line = conn.prepareStatement(
"INSERT INTO order_items (order_id, product_id, quantity, discount_pct) VALUES (?, ?, ?, 0)")) {
ins.setInt(1, 9001); ins.setInt(2, 5); ins.setBigDecimal(3, new BigDecimal("4.90")); ins.setString(4, "Storgatan 1, Luleå");
ins.executeUpdate();
Savepoint sp = conn.setSavepoint("lines");
line.setInt(1, 9001); line.setInt(2, 1379); line.setInt(3, 2);
line.executeUpdate();
// conn.rollback(sp); // would undo only the order line
conn.commit();
} catch (SQLException e) {
conn.rollback();
throw e;
}

setTransactionIsolation() accepts TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ and TRANSACTION_SERIALIZABLE. ((CORADBConnection) conn).setLockTimeout(ms) sets the lock wait timeout of the session. See Transactions and locking.

try (PreparedStatement ps = conn.prepareStatement("UPDATE product SET units_in_stock = units_in_stock + ? WHERE id = ?")) {
ps.setInt(1, 10); ps.setInt(2, 1379); ps.addBatch();
ps.setInt(1, 5); ps.setInt(2, 1224); ps.addBatch();
int[] counts = ps.executeBatch(); // sent in one request
}

For tables with an AUTO_INCREMENT column, request the generated key. With a table created as CREATE TABLE ticket (id INT AUTO_INCREMENT PRIMARY KEY, subject VARCHAR(100)):

try (PreparedStatement ps = conn.prepareStatement(
"INSERT INTO ticket (subject) VALUES (?)", Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, "Late delivery");
ps.executeUpdate();
try (ResultSet keys = ps.getGeneratedKeys()) {
if (keys.next()) System.out.println("new id " + keys.getLong(1));
}
}
  • BLOB / CLOB: use conn.createBlob() / conn.createClob(), or bind a byte[], InputStream, String or Reader with setBytes(), setBinaryStream(), setString() or setCharacterStream(). Read with getBlob() / getClob() and their streams. See BLOB/CLOB.
  • SET, MULTISET, LIST: returned as Java arrays by getObject(); bind them with setObject() and an array.
  • OIDs: object references are returned as coradb.sql.CORADBOID, which can read and update the referenced object.

Errors raised by the server carry the engine error code in SQLException.getErrorCode() (see Error messages). Errors raised by the driver itself use these codes (coradb.jdbc.driver.CORADBJDBCErrorCode):

Code Name Message
-21101 connection_closed Attempt to operate on a closed Connection.
-21102 statement_closed Attempt to access a closed Statement.
-21103 prepared_statement_closed Attempt to access a closed PreparedStatement.
-21104 result_set_closed Attempt to access a closed ResultSet.
-21105 not_supported Not supported method
-21106 invalid_trans_iso_level Unknown transaction isolation level.
-21107 invalid_url invalid URL
-21108 no_dbname The database name should be given.
-21109 invalid_query_type_for_executeQuery The query is not applicable to the executeQuery(). Use the executeUpdate() instead.
-21110 invalid_query_type_for_executeUpdate The query is not applicable to the executeUpdate(). Use the executeQuery() instead.
-21111 negative_value_for_length The length of the stream cannot be negative.
-21112 ioexception_in_stream An IOException was caught during reading the inputstream.
-21113 deprecated Not supported method, because it is deprecated.
-21114 not_numerical_object The object does not seem to be a number.
-21115 invalid_index Missing or invalid position of the bind variable provided.
-21116 invalid_column_name The column name is invalid.
-21117 invalid_row Invalid cursor position.
-21118 conversion_error Type conversion error.
-21119 invalid_tuple Internal error: The number of attributes is different from the expected.
-21120 invalid_value The argument is invalid.
-21121 not_collection The type of the column should be a collection type.
-21122 dbmetadata_closed Attempt to operate on a closed DatabaseMetaData.
-21123 non_scrollable Attempt to call a method related to scrollability of non-scrollable ResultSet.
-21124 non_sensitive Attempt to call a method related to sensitivity of non-sensitive ResultSet.
-21125 non_updatable Attempt to call a method related to updatability of non-updatable ResultSet.
-21126 non_updatable_column Attempt to update a column which cannot be updated.
-21127 invalid_query_type_for_executeInsert The query is not applicable to the executeInsert().
-21128 argument_zero The argument row can not be zero.
-21129 empty_inputstream Given InputStream object has no data.
-21130 empty_reader Given Reader object has no data.
-21131 insertion_query_fail Insertion query failed.
-21132 non_scrollable_statement Attempt to call a method related to scrollability of TYPE_FORWARD_ONLY Statement.
-21133 iss_fail_login Authentication failure
-21134 pooled_connection_closed Attempt to operate on a closed PooledConnection.
-21135 xa_connection_closed Attempt to operate on a closed XAConnection.
-21136 xa_illegal_operation Illegal operation in a distributed transaction
-21137 oid_closed Attempt to access a CORADBOID associated with a Connection which has been closed.
-21138 invalid_table_name The table name is invalid.
-21139 lob_pos_invalid Lob position to write is invalid.
-21140 lob_is_not_writable Lob is not writable.
-21141 request_timeout Request timed out.

The driver implements the standard java.sql / javax.sql interfaces; see the Java SE JDBC documentation. CoraDB-specific classes in coradb.jdbc.driver and coradb.sql:

Class Adds
CORADBDriver The java.sql.Driver (jdbc:coradb: URLs)
CORADBConnection setLockTimeout(int), setCharset(String), setAutoGeneratedKeys(boolean), LOB helpers
CORADBDataSource, CORADBConnectionPoolDataSource, CORADBXADataSource Data sources (see above)
CORADBBlob, CORADBClob LOB implementations
coradb.sql.CORADBOID Object references (OIDs)
coradb.sql.CORADBTimestamp, CORADBTimestamptz Date-time values with CoraDB-specific details
CORADBJDBCErrorCode Driver error codes (see above)