8

根据http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#close()的文档,

当 Statement 对象关闭时,其当前的 ResultSet 对象(如果存在)也将关闭。

但是根据是否必须单独关闭 JDBC 结果集和语句,尽管随后关闭了连接?Connection Statement, 明确关闭和似乎是一个好习惯ResultSet

如果我们仍然需要 close ResultSet,我们可能需要一个嵌套的 try-with-resources 语句,因为我们可能会Statement像这样设置参数:

try (Connection conn = connectionProvider.getConnection();
     PreparedStatement pstmt = conn.prepareStatement(sql) {//resources of conn and pst

     setPrepareStatementParameter(pstmt, kvs);//need to set parameters, so I have to put ResultSet into another try-with-resources statement

     try (ResultSet res = pstmt.executeQuery()) {
                ..............

     }
}

问题:

是否将 ResultSet 放入一个单独的 try-with-resources 语句中,因为文档声明关闭Statement将关闭 ResultSet

4

2 回答 2

4

您的示例涵盖的连接、语句和结果集之间的交互范围太有限。考虑以下:

try (Connection conn = connectionProvider.getConnection();
     PreparedStatement pstmt = conn.prepareStatement(sql);) {

     for (int i = 0; i < kvs.length; i++) {
         setPrepareStatementParameter(pstmt, kvs[i]);

         // do other stuff

         // Place the ResultSet in another try with resources
         // to ensure the previous iteration's ResultSet
         // is closed when the next iteration begins
         try (ResultSet res = pstmt.executeQuery()) {
             ..............

         }
     }
 }

在上面的示例中,PreparedStatement 被参数化并kvs.length在 for 循环中执行了多次。想象一下这样一种情况,其中参数化过程无论出于何种原因都需要很长时间。请注意,关闭 PreparedStatement 对我们没有好处,因为我们希望在 for 循环的每次迭代中重用已编译的 SQL 语句。然后肯定将 ResultSet 嵌套到它自己的 try-with-resources 块中——从而确保先前迭代的 ResultSet 是关闭的,但 PreparedStatement 保持打开状态——是值得付出的努力。

于 2015-02-24T05:28:29.687 回答
0

是的,您应该关闭或为结果集放置一个 try-resources。

为什么?

我引用了我从其他答案中读到的内容,这对我来说很有意义。

  • 理论上关闭语句会关闭结果集。
  • 在实践中,一些错误的 JDBC 驱动程序实现未能做到这一点。

在此处查看完整答案: https ://stackoverflow.com/a/45133734/401529

于 2020-06-24T14:50:55.093 回答