Search code examples
javatry-catchjava-7autocloseable

Java 7, try-with-resources: can i omit creating Connection and PreparedStatement?


Case A:

try (Connection con = DriverManager.getConnection(myConnectionURL);
     PreparedStatement ps = con.prepareStatement("SELECT * FROM table"); 
     ResultSet rs = ps.executeQuery()) {

     processResults(rs);
} catch (SQLException e) {
    e.printStackTrace();
}

Case B:

try (ResultSet rs = DriverManager.getConnection(myConnectionURL)
                                 .prepareStatement("SELECT * FROM table")
                                 .executeQuery()) {
     processResults(rs);
} catch (SQLException e) {
    e.printStackTrace();
}

In the case A con, ps and rs will be closed automatically. What about case B? In the case B the variables con and ps don't create as it was in case A.

My question: are the both cases completely identical? Is there any problems in case B?


Solution

  • Case B is not correct, because neither the Connection nor the PreparedStatement can ever get closed. Only the items which are declared in the try block are auto-closed.