What is considered best practices when cleaning up JDBC resources and why? I kept the example short, thus just the cleaning up of the ResultSet.
finally
{
This is my approach for JDK 6. If you have JDK 7+ you better use the approach I describe here https://stackoverflow.com/a/9200053/259237
private void querySomething() {
Connection connection = null;
PreparedStatement statement = null;
ResultSet rs = null;
try {
// get connection
// prepare statement
// execute query
// and so on
} catch (SQLException e) {
throw new MyException("Error while talking to database", e);
} finally {
close(connection, statement, rs);
}
}
// useful because you probably have more than one method interacting with database
public static void close (Connection connection, Statement statement, ResultSet rs) {
if (rs != null) {
try { rs.close(); } catch (Exception e) { _logger.warning(e.toString()); }
}
if (statement != null) {
try { statement.close(); } catch (Exception e) { _logger.warning(e.toString()); }
}
if (connection != null) {
try { connection.close(); } catch (Exception e) { _logger.warning(e.toString()); }
}
}