Java Database Connectivity - Examples

Examples

The method Class.forName(String) is used to load the JDBC driver class. The line below causes the JDBC driver from some jdbc vendor to be loaded into the application. (Some JVMs also require the class to be instantiated with .newInstance.)

Class.forName( "com.somejdbcvendor.TheirJdbcDriver" );

In JDBC 4.0, it is no longer necessary to explicitly load JDBC drivers using Class.forName. See JDBC 4.0 Enhancements in Java SE 6.

When a Driver class is loaded, it creates an instance of itself and registers it with the DriverManager. This can be done by including the needed code in the driver class's static block. E.g., DriverManager.registerDriver(Driver driver)

Now when a connection is needed, one of the DriverManager.getConnection methods is used to create a JDBC connection.

Connection conn = DriverManager.getConnection( "jdbc:somejdbcvendor:other data needed by some jdbc vendor", "myLogin", "myPassword" ); try { /* you use the connection here */ } finally { //It's important to close the connection when you are done with it try { conn.close; } catch (Throwable ignore) { /* Propagate the original exception instead of this one that you may want just logged */ } }

The URL used is dependent upon the particular JDBC driver. It will always begin with the "jdbc:" protocol, but the rest is up to the particular vendor. Once a connection is established, a statement can be created.

Statement stmt = conn.createStatement; try { stmt.executeUpdate( "INSERT INTO MyTable( name ) VALUES ( 'my name' ) " ); } finally { //It's important to close the statement when you are done with it try { stmt.close; } catch (Throwable ignore) { /* Propagate the original exception instead of this one that you may want just logged */ } }

Note that Connections, Statements, and ResultSets often tie up operating system resources such as sockets or file descriptors. In the case of Connections to remote database servers, further resources are tied up on the server, e.g., cursors for currently open ResultSets. It is vital to close any JDBC object as soon as it has played its part; garbage collection should not be relied upon. Forgetting to close things properly results in spurious errors and misbehaviour. The above try-finally construct is a recommended code pattern to use with JDBC objects.

Data is retrieved from the database using a database query mechanism. The example below shows creating a statement and executing a query.

Statement stmt = conn.createStatement; try { ResultSet rs = stmt.executeQuery( "SELECT * FROM MyTable" ); try { while ( rs.next ) { int numColumns = rs.getMetaData.getColumnCount; for ( int i = 1 ; i <= numColumns ; i++ ) { // Column numbers start at 1. // Also there are many methods on the result set to return // the column as a particular type. Refer to the Sun documentation // for the list of valid conversions. System.out.println( "COLUMN " + i + " = " + rs.getObject(i) ); } } } finally { try { rs.close; } catch (Throwable ignore) { /* Propagate the original exception instead of this one that you may want just logged */ } } } finally { try { stmt.close; } catch (Throwable ignore) { /* Propagate the original exception instead of this one that you may want just logged */ } }

Typically, however, it would be rare for a seasoned Java programmer to code in such a fashion. The usual practice would be to abstract the database logic into an entirely different class and to pass preprocessed strings (perhaps derived themselves from a further abstracted class) containing SQL statements and the connection to the required methods. Abstracting the data model from the application code makes it more likely that changes to the application and data model can be made independently.

An example of a PreparedStatement query, using conn and class from first example.

PreparedStatement ps = conn.prepareStatement( "SELECT i.*, j.* FROM Omega i, Zappa j WHERE i.name = ? AND j.num = ?" ); try { // In the SQL statement being prepared, each question mark is a placeholder // that must be replaced with a value you provide through a "set" method invocation. // The following two method calls replace the two placeholders; the first is // replaced by a string value, and the second by an integer value. ps.setString(1, "Poor Yorick"); ps.setInt(2, 8008); // The ResultSet, rs, conveys the result of executing the SQL statement. // Each time you call rs.next, an internal row pointer, or cursor, // is advanced to the next row of the result. The cursor initially is // positioned before the first row. ResultSet rs = ps.executeQuery; try { while ( rs.next ) { int numColumns = rs.getMetaData.getColumnCount; for ( int i = 1 ; i <= numColumns ; i++ ) { // Column numbers start at 1. // Also there are many methods on the result set to return // the column as a particular type. Refer to the Sun documentation // for the list of valid conversions. System.out.println( "COLUMN " + i + " = " + rs.getObject(i) ); } // for } // while } finally { try { rs.close; } catch (Throwable ignore) { /* Propagate the original exception instead of this one that you may want just logged */ } } } finally { try { ps.close; } catch (Throwable ignore) { /* Propagate the original exception instead of this one that you may want just logged */ } } // try

If a database operation fails, JDBC raises an SQLException. There is typically very little one can do to recover from such an error, apart from logging it with as much detail as possible. It is recommended that the SQLException be translated into an application domain exception (an unchecked one) that eventually results in a transaction rollback and a notification to the user.

An example of a database transaction:

boolean autoCommitDefault = conn.getAutoCommit; try { conn.setAutoCommit(false); /* You execute statements against conn here transactionally */ conn.commit; } catch (Throwable e) { try { conn.rollback; } catch (Throwable ignore) {} throw e; } finally { try { conn.setAutoCommit(autoCommitDefault); } catch (Throwable ignore) {} }

Here are examples of host database types which Java can convert to with a function.

setXXX Methods
Oracle Datatype setXXX
CHAR setString
VARCHAR2 setString
NUMBER setBigDecimal
setBoolean
setByte
setShort
setInt
setLong
setFloat
setDouble
INTEGER setInt
FLOAT setDouble
CLOB setClob
BLOB setBlob
RAW setBytes
LONGRAW setBytes
DATE setDate
setTime
setTimestamp

For an example of a CallableStatement (to call stored procedures in the database), see the Java SE 7.

Read more about this topic:  Java Database Connectivity

Famous quotes containing the word examples:

    No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.
    André Breton (1896–1966)

    Histories are more full of examples of the fidelity of dogs than of friends.
    Alexander Pope (1688–1744)

    It is hardly to be believed how spiritual reflections when mixed with a little physics can hold people’s attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.
    —G.C. (Georg Christoph)