Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new jre7 try block resources

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?


1 Answers

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;
}
like image 128
Yuriy Nakonechnyy Avatar answered Jan 26 '26 00:01

Yuriy Nakonechnyy