Is it a good practice to put ResultSet into a nested try-with-resources statement after Java7?
Your example covers too limited a range of the interactions between Connections, Statements, and ResultSets. Consider the following:
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()) {
..............
}
}
}
In the above example, the PreparedStatement is parametrized and executed a kvs.length
number of times within the for-loop. Imagine a case in which the parametrization process, for any reason, took a significant length of time. Note that closing the PreparedStatement would do us no good since we want to reuse the compiled SQL statement at every iteration of the for-loop. Then surely nesting the ResultSet into its own try-with-resources block---thus ensuring the prior iteration's ResultSet is closed but the PreparedStatement remains open---is a worthwhile effort.