简体   繁体   中英

JDBC connection try with resources use

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM