JDBC连接尝试使用资源

问题描述

我是Java编程的新手,对尝试使用资源有疑问 共享代码

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

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

这会关闭PrepareStatement和db.connection(),还是只关闭PreparedStatement?

解决方法

您显示的代码将关闭准备好的语句,并泄漏。如果要同时关闭两者,则需要在资源块中为每个资源使用一条语句:

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