新的jre7尝试阻止资源 [英] new jre7 try block resources

查看:121
本文介绍了新的jre7尝试阻止资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做

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

当PreparedStatement关闭时,ResultSet是否仍会关闭,还是我仍然会关闭还必须显式关闭ResultSet吗?

Will the ResultSet still be closed when the PreparedStatement is closed, or will I still have to explicitly close the ResultSet also?

推荐答案

根据 javax.sql.Statement.close()方法的JavaDoc:

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


注意:当Statement对象关闭时,它的当前ResultSet对象(如果存在)也会关闭。

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

所以,回答你的问题 - 是的, ResultSet 将在你的情况下自动关闭,因为相关的声明试用资源块中关闭。

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

但请注意显式关闭 ResultSet s是一个很好的做法,建议遵循,因此遵循良好做法的修改后的代码如下所示:

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

这篇关于新的jre7尝试阻止资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆