【问题标题】:Is it a good practice to put ResultSet into a nested try-with-resources statement after Java7?在 Java7 之后将 ResultSet 放入嵌套的 try-with-resources 语句中是一种好习惯吗?
【发布时间】:2015-04-14 04:03:46
【问题描述】:

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

当一个 Statement 对象关闭时,它当前的 ResultSet 对象,如果 一个存在,也是封闭的。

但根据 Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards? ,明确关闭 Connection StatementResultSet 似乎是一个好习惯。

如果我们仍然需要关闭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

【问题讨论】:

    标签: java jdbc try-catch try-with-resources


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      为什么?

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-01
        • 2013-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        • 2012-10-06
        相关资源
        最近更新 更多