Closing Oracle connection?
We always hear that we should close the connection once we are done with a transaction. My question here is: even if we don't close the connection, the garbag开发者_Python百科e collector will reclaim the memory once we are out of the method inside of which we are creating the connection. so what's the actual issue, even if we don't close the connection?
No, GC doesn't help you here, because it's not about memory.
A connection is a scarce resource on the database server, not in your app client. If you clean up your memory without telling the server to do the same you'll leak a connection that may not be reclaimed. Eventually you'll run out.
Same with ResultSet - it's a cursor.
You must always close all SQL resources - Connection, Statement, and ResultSet - in individual finally blocks, wrapped in try/catch blocks, in reverse order of acquisition.
public class JdbcTemplate {
public Object exampleSqlOperation(Connection c) throws SQLException {
Object results = null;
Statement st = null;
ResultSet rs = null;
try {
// SQL stuff here
// Load into results Object - data structure
} catch (SQLException e) {
e.printStackTrace(); // Better to log it.
} finally {
DatabaseUtils.close(rs);
DatabaseUtils.close(st);
}
return results;
}
}
public class DatabaseUtils {
public static void close(Connection c) {
try {
if (c != null) c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// Same for Statement, ResultSet
}
精彩评论