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

192 views Asked by At

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?

2

There are 2 answers

0
user207421 On BEST ANSWER

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.

0
SMA On

Yes you are using try with resource (using JDK 7 or above) so your prepared statement would be closed automatically. See this page for your reference. PreparedStatement/Connection does implement AutoCloseable interface internally which makes perfect sense to use it with try with resource block.

You could try something like:

public void doDbOperation(int id) {
try (Connection con = DriverManager.getConnection(myConnectionURL);
     PreparedStatement ps = createStatement(con, userId); 
     ResultSet rs = ps.executeQuery()) {//auto close

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

private PreparedStatement createStatement(Connection con, int id) throws SQLException {
     String sql = "SELECT myid FROM table WHERE id = ?";
     PreparedStatement ps = con.prepareStatement(sql);
     ps.setInt(1, id);
    return ps;
}

private void processResults(ResultSet rs) { 
   // business logic
}