gpt4 book ai didi

java - JDBC 连接尝试与资源使用

转载 作者:行者123 更新时间:2023-12-04 01:13:17 26 4
gpt4 key购买 nike

我是 Java 编程的新手,对 try with resources uses 有疑问分享代码

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?

最佳答案

如图所示,您的代码将关闭准备好的语句,并泄漏连接。如果你想关闭两者,你需要在资源 block 中为每个资源使用一个语句:

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

关于java - JDBC 连接尝试与资源使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64144096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com