Versions available for this page: CUBRID 8.2.1 | CUBRID 8.3.0 | CUBRID 8.3.1 | CUBRID 8.4.0 | CUBRID 8.4.1 | CUBRID 8.4.3 | CUBRID 9.0.0 |
The DriverManager is an interface for managing the JDBC driver. It is used to select a driver and create new database connection. If CUBRID JDBC driver is registered, you can connect a database by calling the DriverManager.getConnection(db-url, user-id, password) method. The getConnection method returns the Connection object and it is used to execute queries and commands, and commit and roll back transactions. The syntax below shows the db-url argument for configuring connection.
jdbc:cubrid:< host> :< port> :< db-name> :[user-id]:[password]:[?< property> [& < property> ]]
< host> ::=
hostname | ip_address
< property> ::=
altHosts=< alternative_hosts> | rcTime=< second> | connectTimeout=< second> | queryTimeout=< second> | charSet=< character_set> | zeroDateTimeBehavior=< behavior_type> | logFile=< file_name> | logOnException=< bool_type> | logSlowQueries=< bool_type> & slowQueryThresholdMillis=< millisecond>
< alternative_hosts> ::=
< standby_broker1_host> :< port> [,< standby_broker2_host> :< port> ]
< behavior_type> ::= exception | round | convertToNull
< bool_type> ::= true | false
--connection URL string when user name and password omitted
URL=jdbc:CUBRID:192.168.0.1:33000:db1:::
--connection URL string when zeroDateTimeBehavior property specified
URL=jdbc:CUBRID:127.0.0.1:31000:db1:::?zeroDateTimeBehavior=convertToNull
--connection URL string when charSet property specified
URL=jdbc:CUBRID:192.168.0.1:33000:db1:::?charSet=utf-8
--connection URL string when queryTimeout and charSet property specified
URL=jdbc:CUBRID:127.0.0.1:31000:db1:::?queryTimeout=1& charSet=utf-8
--connection URL string when a property(altHosts) specified for HA
URL=jdbc:CUBRID:192.168.0.1:33000:db1:::?altHosts=192.168.0.2:33000,192.168.0.3:33000
--connection URL string when properties(altHosts,rcTime, connectTimeout) specified for HA
URL=jdbc:CUBRID:192.168.0.1:33000:db1:::?altHosts=192.168.0.2:33000,192.168.0.3:33000& rcTime=600& connectTimeout=5
--connection URL string when properties(altHosts,rcTime, charSet) specified for HA
URL=jdbc:CUBRID:192.168.0.1:33000:db1:::?altHosts=192.168.0.2:33000,192.168.0.3:33000& rcTime=600& charSet=utf-8
String url = " jdbc:cubrid:192.168.0.1:33000:demodb:::"
String userid = " "
String password = " "
try {
Connection conn =
DriverManager.getConnection(url,userid,password)
// Do something with the Connection
...
} catch (SQLException e) {
System.out.println(" SQLException:" + e.getMessage())
System.out.println(" SQLState: " + e.getSQLState())
}
...
Note The rollback method requesting transaction rollback will exit after a server complete the rollback job.
You can check foreign key information by using getImportedKeys, getExportedKeys, and getCrossReference methods of the DatabaseMetaData interface. The usage and example of each method are as follows:
getImportedKeys(String catalog, String schema, String table)
getExportedKeys(String catalog, String schema, String table)
getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable)
When the methods above are called, the ResultSet consisting of 14 columns listed in the table below is returned.
|
Name |
Type |
Note |
|---|---|---|
|
PKTABLE_CAT |
String |
null without exception |
|
PKTABLE_SCHEM |
String |
null without exception |
|
PKTABLE_NAME |
String |
The name of a primary key table |
|
PKCOLUMN_NAME |
String |
The name of a primary key column |
|
FKTABLE_CAT |
String |
null without exception |
|
FKTABLE_SCHEM |
String |
null without exception |
|
FKTABLE_NAME |
String |
The name of a foreign key table |
|
FKCOLUMN_NAME |
String |
The name of a foreign key column |
|
KEY_SEQ |
short |
Sequence of columns of foreign keys or primary keys (starting from 1) |
|
UPDATE_RULE |
short |
The corresponding values to referring actions defined as to foreign keys when primary keys are updated. |
|
DELETE_RULE |
short |
The corresponding value to referring actions defined as to foreign keys when primary keys are deleted. |
|
FK_NAME |
String |
Foreign key name |
|
PK_NAME |
String |
Primary key name |
|
DEFERRABILITY |
short |
6 without exception (DatabaseMetaData.importedKeyInitiallyImmediate) |
ResultSet rs = null
DatabaseMetaData dbmd = conn.getMetaData()
System.out.println(" ===== Test getImportedKeys" )
System.out.println(" =====" )
rs = dbmd.getImportedKeys(null, null, " pk_table" )
Test.printFkInfo(rs)
rs.close()
System.out.println(" ===== Test getExportedKeys" )
System.out.println(" =====" )
rs = dbmd.getExportedKeys(null, null, " fk_table" )
Test.printFkInfo(rs)
rs.close()
System.out.println(" ===== Test getCrossReference" )
System.out.println(" =====" )
rs = dbmd.getCrossReference(null, null, " pk_table" , null, null, " fk_table" )
Test.printFkInfo(rs)
rs.close()
In addition to the methods defined in the JDBC specification, CUBRID JDBC driver provides methods that handle OIDs and collections (set, multiset, and sequence).
To use these methods, you must import cubrid.sql.* as well as the CUBRID JDBC driver classes which are imported by default. Furthermore, you should convert to not the ResultSet class, which is provided by the standard JDBC API) but the CUBRIDResultSet class to get result.
import cubrid.jdbc.driver.*
import cubrid.sql.*
...
CUBRIDResultSet urs = (CUBRIDResultSet) stmt.executeQuery(
" SELECT city FROM location" )
Warning If extended API is used, transactions won't be automatically committed even though AUTOCOMMIT is set to TRUE. Therefore, you must explicitly commit transactions for open connections. The extended API of CUBRID is method that handle OIDs, collections, etc.
You must follow the rules below when using OIDs.
Example
import java.sql.*
import cubrid.sql.* //a
import cubrid.jdbc.driver.*
/*
CREATE TABLE oid_test(
id INTEGER,
name VARCHAR(10),
age INTEGER
)
INSERT INTO oid_test VALUES(1, 'Laura', 32)
INSERT INTO oid_test VALUES(2, 'Daniel', 39)
INSERT INTO oid_test VALUES(3, 'Stephen', 38)
*/
class OID_Sample
{
public static void main (String args [])
{
// Making a connection
String url= " jdbc:cubrid:localhost:33000:demodb:::"
String user = " dba"
String passwd = " "
// SQL statement to get OID values
String sql = " SELECT oid_test from oid_test" //b
// columns of the table
String[] attr = { " id" , " name" , " age" }
// Declaring variables for Connection and Statement
Connection con = null
Statement stmt = null
CUBRIDResultSet rs = null
ResultSetMetaData rsmd = null
try {
Class.forName(" cubrid.jdbc.driver.CUBRIDDriver" )
} catch (ClassNotFoundException e) {
throw new IllegalStateException(" Unable to load Cubrid driver" , e)
}
try {
con = DriverManager.getConnection(url, user, passwd)
stmt = con.createStatement()
rs = (CUBRIDResultSet)stmt.executeQuery(sql) //c
rsmd = rs.getMetaData()
// Printing columns
int numOfColumn = rsmd.getColumnCount()
for (int i = 1 i < = numOfColumn i++ ) {
String ColumnName = rsmd.getColumnName(i)
String JdbcType = rsmd.getColumnTypeName(i)
System.out.print(ColumnName )
System.out.print(" (" + JdbcType + " )" )
System.out.print(" | " )
}
System.out.print(" " )
// Printing rows
CUBRIDResultSet rsoid = null
int k = 1
while (rs.next()) {
CUBRIDOID oid = rs.getOID(1) //d
System.out.print(" OID" )
System.out.print(" | " )
rsoid = (CUBRIDResultSet)oid.getValues(attr) //e
while (rsoid.next()) {
for( int j=1 j < = attr.length j++ ) {
System.out.print(rsoid.getObject(j))
System.out.print(" | " )
}
}
System.out.print(" " )
// New values of the first row
Object[] value = { 4, " Yu-ri" , 19 }
if (k == 1) oid.setValues(attr, value) //f
k = 0
}
con.commit() //g
} catch(CUBRIDException e) {
e.printStackTrace()
} catch(SQLException ex) {
ex.printStackTrace()
} finally {
if(rs != null) try { rs.close() } catch(SQLException e) {}
if(stmt != null) try { stmt.close() } catch(SQLException e) {}
if(con != null) try { con.close() } catch(SQLException e) {}
}
}
}
The line " a" in the example 1 is where data of collection types (SET, MULTISET, and LIST) is fetched from CUBRIDResultSet. The results are returned as array format. Note that this can be used only when data types of all elements defined in the collection types are same.
Example 1
import java.sql.*
import java.lang.*
import cubrid.sql.*
import cubrid.jdbc.driver.*
// create class collection_test(
// settest set(integer),
// multisettest multiset(integer),
// listtest list(Integer)
// )
//
// insert into collection_test values({1,2,3},{1,2,3},{1,2,3})
// insert into collection_test values({2,3,4},{2,3,4},{2,3,4})
// insert into collection_test values({3,4,5},{3,4,5},{3,4,5})
class Collection_Sample
{
public static void main (String args [])
{
String url= " jdbc:cubrid:127.0.0.1:33000:demodb:::"
String user = " "
String passwd = " "
String sql = " select settest,multisettest,listtest from collection_test"
try {
Class.forName(" cubrid.jdbc.driver.CUBRIDDriver" )
} catch(Exception e){
e.printStackTrace()
}
try {
Connection con = DriverManager.getConnection(url,user,passwd)
Statement stmt = con.createStatement()
CUBRIDResultSet rs = (CUBRIDResultSet) stmt.executeQuery(sql)
CUBRIDResultSetMetaData rsmd = (CUBRIDResultSetMetaData) rs.getMeta Data()
int numbOfColumn = rsmd.getColumnCount()
while (rs.next ()) {
for (int j=1 j< =numbOfColumn j++ ) {
Object[] reset = (Object[]) rs.getCollection(j) //a
for (int m=0 m < reset.length m++)
System.out.print(reset[m] +" ," )
System.out.print(" | " )
}
System.out.print(" " )
}
rs.close()
stmt.close()
con.close()
} catch(SQLException e) {
e.printStackTrace()
}
}
}
Example 2
import java.sql.*
import java.io.*
import java.lang.*
import cubrid.sql.*
import cubrid.jdbc.driver.*
// create class collection_test(
// settest set(integer),
// multisettest multiset(integer),
// listtest list(Integer)
// )
//
// insert into collection_test values({1,2,3},{1,2,3},{1,2,3})
// insert into collection_test values({2,3,4},{2,3,4},{2,3,4})
// insert into collection_test values({3,4,5},{3,4,5},{3,4,5})
class SetOP_Sample
{
public static void main (String args [])
{
String url = " jdbc:cubrid:127.0.0.1:33000:demodb:::"
String user = " "
String passwd = " "
String sql = " select collection_test from collection_test"
try {
Class.forName(" cubrid.jdbc.driver.CUBRIDDriver" )
} catch(Exception e){
e.printStackTrace()
}
try {
CUBRIDConnection con =(CUBRIDConnection)
DriverManager.getConnection(url,user,passwd)
Statement stmt = con.createStatement()
CUBRIDResultSet rs = (CUBRIDResultSet)stmt.executeQuery(sql)
while (rs.next ()) {
CUBRIDOID oid = rs.getOID(1)
oid.addToSet(" settest" ,new Integer(10))
oid.addToSet(" multisettest" ,new Integer(20))
oid.addToSequence(" listtest" ,1,new Integer(30))
oid.addToSequence(" listtest" ,100,new Integer(100))
oid.putIntoSequence(" listtest" ,99,new Integer(99))
oid.removeFromSet(" settest" ,new Integer(1))
oid.removeFromSet(" multisettest" ,new Integer(2))
oid.removeFromSequence(" listtest" ,99)
oid.removeFromSequence(" listtest" ,1)
}
con.commit()
rs.close()
stmt.close()
con.close()
} catch(SQLException e) {
e.printStackTrace()
}
}
}
Auto increment (AUTO_INCREMENT) is a column-related feature that increments the numeric value of each row. For more information, see " CUBRID SQL Guide > Table Definition > CREATE TABLE > Column Definition." It can be defined only for numeric domains (SMALLINT, INTEGER, DECIMAL(p, 0), and NUMERIC(p, 0)).
Auto increment is recognized as automatically created keys in the JDBC programs. To retrieve the key, you need to specify the time to insert a row from which the automatically created key value is to be retrieved. To perform it, you must set the flag by calling Connection.prepareStatement and Statement.execute methods. In this case, the command executed should be the INSERT statement or INSERT within SELECT statement. For other commands, the JDBC driver ignores the flag-setting parameter.
The following example shows how to create a table with auto increment, enter data into the table so that automatically created key values are entered into auto increment columns, and check whether the key values are successfully retrieved by using the Statement.getGeneratedKeys() method. Each step is explained in the comments for commands that correspond to the steps above.
import java.sql.*
import java.math.*
import cubrid.jdbc.driver.*
Connection con
Statement stmt
ResultSet rs
java.math.BigDecimal iDColVar
...
stmt = con.createStatement() // Create a Statement object
stmt.executeUpdate(
" CREATE TABLE EMP_PHONE (EMPNO CHAR(6), PHONENO CHAR(4), "
+ " IDENTCOL INTEGER AUTO_INCREMENT)" ) // Create table with identity column
stmt.execute(
" INSERT INTO EMP_PHONE (EMPNO, PHONENO) "
+ " VALUES ('000010', '5555')" , // Insert a row < Step 1>
Statement.RETURN_GENERATED_KEYS) // Indicate you want automatically
rs = stmt.getGeneratedKeys() // generated keys
// Retrieve the automatically < Step 2>
// generated key value in a ResultSet.
// Only one row is returned.
// Create ResultSet for query
while (rs.next()) {
java.math.BigDecimal idColVar = rs.getBigDecimal(1)
// Get automatically generated key
// value
System.out.println(" automatically generated key value = " + idColVar)
}
rs.close() // Close ResultSet
stmt.close() // Close Statement
The interface that handles LOB data in JDBC is implemented based on JDBC 4.0 specification. The constraints of the interface are as follows:
// JDK 1.6 or later
import java.sql.*
Connection conn = DriverManager.getConnection(url, id, passwd)
Blob blob = conn.createBlob()
…
// JDK 1.6 or earlier
import java.sql.*
import cubrid.jdbc.driver.*
Connection conn = DriverManager.getConnection(url, id, passwd)
Blob blob = ((CUBRIDConnection)conn).createBlob()
…
You can bind the LOB type data in the following ways.
Example 1
Class.forName(" cubrid.jdbc.driver.CUBRIDDriver" )
Connection conn = DriverManager.getConnection (" jdbc:cubrid:localhost:33000:image_db:::" , " " , " " )
PreparedStatement pstmt1 = conn.prepareStatement(" INSERT INTO doc(image_id, doc_id, image) VALUES (?,?,?)" )
pstmt1.setString(1, " image-21" )
pstmt1.setString(2, " doc-21" )
//Creating an empty file in the file system
Blob bImage = conn.createBlob()
byte[] bArray = new byte[256]
…
//Inserting data into the external file. Position is start with 1.
bImage.setBytes(1, bArray)
//Appending data into the external file
bImage.setBytes(257, bArray)
…
pstmt1.setBlob(3, bImage)
pstmt1.executeUpdate()
…
Example 2
Class.forName(" cubrid.jdbc.driver.CUBRIDDriver" )
Connection conn = DriverManager.getConnection (" jdbc:cubrid:localhost:33000:image_db:::" , " " , " " )
conn.setAutoCommit(false)
PreparedStatement pstmt1 = conn.prepareStatement(" SELECT image FROM doc WHERE image_id = ? " )
pstmt1.setString(1, " image-21" )
ResultSet rs = pstmt1.executeQuery()
while (rs.next())
{
Blob bImage = rs.getBlob(1)
PreparedStatement pstmt2 = conn.prepareStatement(" INSERT INTO doc(image_id, doc_id, image) VALUES (?,?,?)" )
pstmt2.setString(1, " image-22" )
pstmt2.setString(2, " doc-22" )
pstmt2.setBlob(3, bImage)
pstmt2.executeUpdate()
pstmt2.close()
}
pstmt1.close()
conn.commit()
conn.setAutoCommit(true)
conn.close()
…
You can get the LOB type data in the following ways.
Example 1
Connection conn = DriverManager.getConnection (" jdbc:cubrid:localhost:33000:image_db:::" , " " , " " )
// Getting data directly from ResetSet
PrepareStatement pstmt1 = conn.prepareStatement(" SELECT content FROM doc_t WHERE doc_id = ? " )
pstmt2.setString(1, " doc-10" )
ResultSet rs = pstmt1.executeQuery()
while (rs.next())
{
String sContent = rs.getString(1)
System.out.println(" doc.content= " +sContent.)
}
Example 2
Connection conn = DriverManager.getConnection (" jdbc:cubrid:localhost:33000:image_db:::" , " " , " " )
// Getting BLOB data from ResultSet and getting data from the BLOB object
PrepareStatement pstmt2 = conn.prepareStatement(“SELECT image FROM image_t WHERE image_id = ?”)
pstmt2.setString(1,”image-20”)
ResultSet rs = pstmt2.executeQuery()
while (rs.next())
{
Blob bImage = rs.getBlob(1)
Bytes[] bArray = bImange.getBytes(1, (int)bImage.length())
}
Note If a string longer than defined max length is inserted (INSERT) or updated (UPDATE), the string will be truncated.
Note To get the latest information about JDBC driver, click http://www.cubrid.org/wiki_apis/entry/cubrid-jdbc-driver.