If I do something like
try (
Connection conn = Database.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM table WHERE something = ? LIMIT 1");
) {
ps.setString(1, "hello world");
ResultSet results = ps.executeQuery();
if(results.next()) {
// blah
}
} catch(SQLException e) {
e.printStackTrace();
}
Will the ResultSet still be closed when the PreparedStatement is closed, or will I still have to explicitly close the ResultSet also?
As per javax.sql.Statement.close() method’s JavaDoc:
So, answering your question – yes,
ResultSetwill be automatically closed in your case, because relatedStatementis closed intry-with-resourcesblock.However, please note that explicitly closing
ResultSets is a good practice which is recommended to follow, so your modified code following good practices would look like: