英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论