In the try-with-resources block, only resources in the try will be automatically closed by the try-with-resources construct. Other resources within the block are unconnected and must be managed (*) .
However, you can put multiple resources in a try , instead of using multiple try-with-resources (one for each resource), for example:
try (PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery()) { while (rs.next()) { System.out.println(rs.getString("email")); System.out.println(rs.getString("password")); } }
(*) As noted in a comment by @ alexander-farber , there are also some resources that are automatically closed by another mechanism, for example, a ResultSet closed when the Statement that generated it is closed. Although you do not use these resources explicitly, they are controlled by their implementation.
janos source share