Is it mandatory to put inner try-with-resources or everything inside one of the try-with-resources will be autoclosed?
try (BasicDataSource ds = BasicDataSourceFactory.createDataSource(dsProperties)) {
// still necessary for Connection to close if inside
// try-with-resources?
try (Connection conn = ds.getConnection()) {
String sql = "SELECT * FROM users";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("email"));
System.out.println(rs.getString("password"));
}
}
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
In a try-with-resources block, only the resources in the try
statement will be closed automatically by the try-with-resources construct. Other resources within the block are unrelated, and must be managed(*).
However, you can put multiple resources in the try
statement,
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 @alexander-farber pointed out in a comment, there are also some resources that get closed automatically by other mechanism, for example a ResultSet
gets closed when the Statement
that generated it gets closed. Although you don't manage those resources explicitly, they are managed by their implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With