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
}