0

案例一:

try (Connection con = DriverManager.getConnection(myConnectionURL);
     PreparedStatement ps = con.prepareStatement("SELECT * FROM table"); 
     ResultSet rs = ps.executeQuery()) {

     processResults(rs);
} catch (SQLException e) {
    e.printStackTrace();
}

案例B:

try (ResultSet rs = DriverManager.getConnection(myConnectionURL)
                                 .prepareStatement("SELECT * FROM table")
                                 .executeQuery()) {
     processResults(rs);
} catch (SQLException e) {
    e.printStackTrace();
}

A 的情况下con将自动关闭。案例B呢?在B 的情况下,变量不会像在A 的情况下那样创建。 psrsconps

我的问题:这两种情况完全一样吗?案例B有什么问题吗?

4

2 回答 2

1

案例 B 不正确,因为 theConnection和 thePreparedStatement都不能关闭。只有在块中声明try的项目才会自动关闭。

于 2015-10-06T01:28:36.390 回答
0

是的,您正在使用资源尝试(使用 JDK 7 或更高版本),因此您准备好的语句将自动关闭。请参阅页面以供参考。PreparedStatement/Connection 确实在内部实现了 AutoCloseable 接口,这非常适合将它与资源块一起使用。

您可以尝试以下方法:

public void doDbOperation(int id) {
try (Connection con = DriverManager.getConnection(myConnectionURL);
     PreparedStatement ps = createStatement(con, userId); 
     ResultSet rs = ps.executeQuery()) {//auto close

     processResults(rs);
} catch (SQLException e) {
    e.printStackTrace();
}
return users;
}

private PreparedStatement createStatement(Connection con, int id) throws SQLException {
     String sql = "SELECT myid FROM table WHERE id = ?";
     PreparedStatement ps = con.prepareStatement(sql);
     ps.setInt(1, id);
    return ps;
}

private void processResults(ResultSet rs) { 
   // business logic
}
于 2014-12-15T12:02:41.270 回答