new jre7 try block resources

∥☆過路亽.° 提交于 2019-12-06 03:37:11

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;
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!