Java 7,try-with-resources:我可以省略创建连接和准备语句吗?



情况 A:

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的情况下psrs将自动关闭。案例B呢?在案例 B 中,变量conps不会像在情况 A 中那样创建。

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

情况 B 是不正确的,因为ConnectionPreparedStatement都无法关闭。只有try块中声明的项目才会自动关闭。

是的,您正在使用 try with resource(使用 JDK 7 或更高版本(,因此您的准备语句将自动关闭。请参阅此页面供您参考。PreparedStatement/Connection 确实在内部实现了 AutoCloseable 接口,这对于与 try with resource block 一起使用非常有意义。

您可以尝试如下操作:

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
}

最新更新