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 ...