gpt4 book ai didi

java - 新的 jre7 try block 资源

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:21:48 25 4
gpt4 key购买 nike

如果我做类似的事情

    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?

最佳答案

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

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

那么,回答您的问题 - 是的,ResultSet将在您的案例中自动关闭,因为相关 Statementtry-with-resources 关闭 block 。

但是,请注意显式关闭ResultSet s 是一个推荐遵循的良好实践,因此您按照良好实践修改后的代码如下所示:

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

关于java - 新的 jre7 try block 资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11320196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com