JDBC connection try with resources use

Viewed 97

I am new to Java programming, having a doubt on try with resources uses sharing the code

String statement= "<statement>";
DataSource ds = createDSConnection();
if (ds == null) return;

try (PreparedStatement prepare = ds.getConnection().prepareStatement(statement)) {
    // statement values
    prepare.execute();
} catch (Exception e) {
}

Will this close both PrepareStatement and as well as db.connection(), or will it just just close PreparedStatement only?

1 Answers

Your code as shown will only close the prepared statement, and leak the connection. If you want to close both, you need to use a statement per resource in the resources block:

try (Connection connection = ds.getConnection();
     PreparedStatement prepare = connection.prepareStatement(statement)) {
    // your code here
}
Related