JDBC连接尝试与资源使用

huangapple go评论76阅读模式
英文:

JDBC connection try with resources use

问题

这将关闭PreparedStatement以及数据库连接(db.connection())。

英文:

I am new to Java programming, having a doubt on try with resources uses
sharing the code

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

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

Will this close both PrepareStatement and as well as db.connection(), or will it just just close PreparedStatement only?

答案1

得分: 4

你的代码如所示,将仅会关闭预准备语句,而会导致连接泄漏。如果你想同时关闭两者,你需要在资源块中为每个资源使用一个语句:

try (Connection connection = ds.getConnection();
     PreparedStatement prepare = connection.prepareStatement(statement)) {
    // 在这里写入你的代码
}
英文:

Your code as shown will only close the prepared statement, and leak the connection. If you want to close both, you need to use a statement per resource in the resources block:

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

huangapple
  • 本文由 发表于 2020年10月1日 02:58:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/64144096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定