I am getting a little confused, I was reading the below from http://en.wikipedia.org/wiki/Java_Database_Connectivity
Connection conn = DriverManager.getConnection(
"jdbc:somejdbcvendor:other data needed by some jdbc vendor",
"myLogin",
"myPassword" );
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
stmt.close();
}
Do you not need to close the conn Connection? What is really happening if the conn.close() doesn't occur?
I have a private web app I'm maintaining that doesn't currently close either form, but is the important one really the stmt one, the conn one, or both?
The site keeps going down intermittently but the server keeps saying it's a database connection issue, my suspicion is that it's not being closed, but I don't know which if any to close.
When you are done with using your Connection
, you need to explicitly close it by calling its close()
method in order to release any other database resources (cursors, handles, etc) the connection may be holding on to.
Actually, the safe pattern in Java is to close your ResultSet
, Statement
, and Connection
(in that order) in a finally
block when you are done with them, something like that:
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// Do stuff
...
} catch (SQLException ex) {
// Exception handling stuff
...
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) { /* ignored */}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) { /* ignored */}
}
}
The finally
block can be slightly improved into (to avoid the null check):
} finally {
try { rs.close(); } catch (Exception e) { /* ignored */ }
try { ps.close(); } catch (Exception e) { /* ignored */ }
try { conn.close(); } catch (Exception e) { /* ignored */ }
}
But, still, this is extremely verbose so you generally end up using an helper class to close the objects in null-safe helper methods and the finally
block becomes something like that:
} finally {
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(ps);
DbUtils.closeQuietly(conn);
}
And, actually, the Apache Commons DbUtils has a DbUtils
class which is precisely doing that so there is no need to write your own.