Should I declare EVERY resource in try-with-resources Statement?

edyucheng :

In many try-with-resource examples I have searched, Statement and ResultSet are declared separately. As the Java document mentioned, the close methods of resources are called in the opposite order of their creation.

try (Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(sql) ) {

} catch (Exception e) {

}

But now I have multiple queries in my function.

Can I make Statement and ResultSet in just one line ? My code is like:

try (ResultSet rs = con.createStatement().executeQuery(sql);
     ResultSet rs2 = con.createStatement().executeQuery(sql2);
     ResultSet rs3 = con.createStatement().executeQuery(sql3)) {

} catch (Exception e) {

}

If I only declare them in one line, does it still close resource of both ResultSet and Statement?

GhostCat salutes Monica C. :

When you have a careful look you will see that the concept is called try-with-resources.

Note the plural! The whole idea is that you can declare one or more resources in that single statement and the jvm guarantees proper handling.

In other words: when resources belong together semantically, it is good practice to declare them together.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=158757&siteId=1