3

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?

2 Answers2

4

As per javax.sql.Statement.close() method's JavaDoc:

Note:When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

So, answering your question - yes, ResultSet will be automatically closed in your case, because related Statement is closed in try-with-resources block.

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:

try (
    Connection conn = Database.getConnection();
    PreparedStatement ps = prepareStatement(conn, "SELECT * FROM table WHERE something = ? LIMIT 1", param);
    ResultSet results = ps.executeQuery();
) {        
    if(results.next()) {
        // blah
    }
} catch(SQLException e) {
    e.printStackTrace();
}

private static PreparedStatement prepareStatement(Connection connection, String sql, String param) throws SQLException {
    final PreparedStatement ps = conn.prepareStatement(sql);
    ps.setString(1, param);
    return ps;
}
Yuriy Nakonechnyy
  • 3,742
  • 4
  • 29
  • 41
  • 1
    Shouldn' there in the signature of prepareStatement method be an exception thrown, I think SQLException? – tomasz_kusmierczyk Jan 12 '14 at 23:26
  • 1
    See [this question](http://stackoverflow.com/q/103938/642706) for other reasons to always close your ResultSet explicitly (or have it closed with a try-with-resources syntax). Design limitations and bugs all too commonly found in JDBC drivers, connection pools, and databases can all cause problems with unclosed ResultSets. – Basil Bourque Mar 17 '14 at 22:15
0

Always As a good practice, try to close your ResultSets and PreparedStatements. In a finally block. Every single time , managing exceptions, so you won't leave resources unattended (is a common source of leaks).

Unless you inject them to the method, hence the calling method probably needs them.

EDIT: Stand corrected. If resultset was created as try-with-resource, will die with your PS.

Alfabravo
  • 7,493
  • 6
  • 46
  • 82
  • "In a finally block. Every single time." Not true. The point of `try-with-resources` is so you don't have to do that, however it doesn't apply to the `ResultSet` in his case. – Dave L. Jul 03 '12 at 23:05