【发布时间】: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 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()) {
..............
}
}
问题:
是否将 ResultSet 放入一个单独的 try-with-resources 语句中,因为文档声明关闭 Statement 将关闭 ResultSet
【问题讨论】:
标签: java jdbc try-catch try-with-resources