JDBC连接尝试与资源使用

Posted

技术标签:

【中文标题】JDBC连接尝试与资源使用【英文标题】:JDBC connection try with resources use 【发布时间】:2020-09-30 18:58:48 【问题描述】:

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

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

以上是关于JDBC连接尝试与资源使用的主要内容,如果未能解决你的问题,请参考以下文章