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?
Case B is not correct, because neither the
Connection
nor thePreparedStatement
can ever get closed. Only the items which are declared in thetry
block are auto-closed.