Is it good practice to put a ResultSet in a nested try-with-resources statement after Java7?

According to the document http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#close () ,

When a Statement object is closed, its current ResultSet, if one exists, is also closed.

But if you do not agree with the Mandatory JDBC results and statements should be closed separately, although the connection is closed afterwards? It seems like a good practice to explicitly close the Connection Statement and ResultSet .

If we still need to close the ResultSet , we may need a nested try-with-resources statement, since we can probably set the parameter for Statement as follows:

 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()) { .............. } } 

Question:

Puts the ResultSet in a separate try-with-resources statement, which is worth something, as the document indicates that closing the Statement closes the ResultSet

+6
source share
1 answer

In this example, the range of interactions between Connections, Applications, and ResultSets is too limited. 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 ResultSet // is closed when the next iteration begins try (ResultSet res = pstmt.executeQuery()) { .............. } } } 

In the above example, PreparedStatement is parameterized and kvs.length is kvs.length number of times inside the for loop. Imagine a case where the parameterization process for some reason took considerable time. Note that closing PreparedStatement will not do us any good, since we want to reuse the compiled SQL statement at each iteration of the for loop. Then be sure to embed the ResultSet in your own try-with-resources block, thereby ensuring that the previous iteration of the ResultSet is closed, but the PreparedStatement remains open - it's worth the effort.

+4
source

Source: https://habr.com/ru/post/982420/


All Articles