【问题标题】:JDBC connection try with resources useJDBC连接尝试与资源使用
【发布时间】: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?

【问题讨论】:

    标签: java jdbc try-with-resources


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 2022-07-20
      • 1970-01-01
      相关资源
      最近更新 更多