2
votes

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?

2

2 Answers

1
votes

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.

0
votes

Yes, and it works exactly as you put it in your question, multiple statements separated by semicolon.

You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:

 try (
    java.util.zip.ZipFile zf =
         new java.util.zip.ZipFile(zipFileName);
    java.io.BufferedWriter writer = 
        java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
) {
    // Enumerate each entry
    for (java.util.Enumeration entries =
                            zf.entries(); entries.hasMoreElements();) {
        // Get the entry name and write it to the output file
        String newLine = System.getProperty("line.separator");
        String zipEntryName =
             ((java.util.zip.ZipEntry)entries.nextElement()).getName() +
             newLine;
        writer.write(zipEntryName, 0, zipEntryName.length());
    }
}

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

ResultSet implements AutoCloseable, which means try-with-resources will also enforce closing it when it finishes using it.

https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html