Jas*_*key 7 java jdbc try-catch try-with-resources
根据http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#close()的文档,
关闭Statement对象时,其当前ResultSet对象(如果存在)也将关闭.
但是,虽然Connection之后关闭了,但是必须单独关闭必须JDBC结果集和语句?,明确关闭Connection Statement和似乎是一个好习惯ResultSet.
如果我们仍然需要关闭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()) {
..............
}
}
Run Code Online (Sandbox Code Playgroud)
是否将ResultSet放入单独的try-with-resources语句中,因为doc声明Statementclose将关闭ResultSet
您的示例涵盖的连接、语句和结果集之间的交互范围太有限。考虑以下:
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()) {
..............
}
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,PreparedStatement 被参数化并kvs.length在 for 循环中执行多次。想象一下这样一种情况,其中参数化过程由于某种原因而花费了相当长的时间。请注意,关闭PreparedStatement 对我们没有任何好处,因为我们希望在for 循环的每次迭代中重用已编译的SQL 语句。然后,将 ResultSet 嵌套到它自己的 try-with-resources 块中 — 从而确保先前迭代的 ResultSet 关闭,但PreparedStatement 保持打开 — 是一项值得付出的努力。