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.
source share