Skip to Main Content
Java Enterprise Best Practices
book

Java Enterprise Best Practices

by O'Reilly Java Authors
December 2002
Intermediate to advanced content levelIntermediate to advanced
288 pages
9h 46m
English
O'Reilly Media, Inc.
Content preview from Java Enterprise Best Practices

Close Statements and Result Sets

According to the JDBC specification, closing a database connection closes all open statement and result set resources associated with that connection. Theoretically, you should never have to close anything but connection instances unless you are intentionally keeping the connection open for a long time. Unfortunately, there are several drivers that do not appropriately clean up the underlying result set and statement resources unless you explicitly close them.

The following code can be used as a template for all JDBC access to ensure that all resources are properly cleaned up:

PreparedStatement stmt = null;
Connection conn = null;
ResultSet rs = null;
   
try {
    InitialContext ctx = new InitialContext(  );
    DataSource ds = (DataSource)ctx.lookup("dsn");
   
    conn = ds.getConnection(  );
    // Do your database access here!
}
catch( SQLException e ) {
    // Handle the error appropriately here.
}
catch( NamingException e ) {
    // Handle the error appropriately here.
}
finally {
    if( rs != null ) {
        try { rs.close(  ); }
        catch( SQLException e ) { // Handle}
    }
    if( stmt != null ) {
        try { stmt.close(  ); }
        catch( SQLException e ) { // Handle}
    }
    if( conn != null ) {
        try { conn.close(  ); }
        catch( SQLException e ) { // Handle}
    }
}

This code ensures that no matter what awful things occur in your application, you will never leave any database resources open! The only truly controversial element in this code lies in the eating of the SQL exceptions when the resources are closed. If you ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Moving to Java 9: Better Design and Simpler Code

Moving to Java 9: Better Design and Simpler Code

Trisha Gee
Java EE 8 High Performance

Java EE 8 High Performance

Romain Manni-Bucau

Publisher Resources

ISBN: 0596003846Supplemental ContentErrata Page