繁体   English   中英

JDBC 连接尝试与资源使用

[英]JDBC connection try with resources use

我是 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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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