如何解决JDBC连接尝试使用资源
我是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?
解决方法
您显示的代码将仅关闭准备好的语句,并泄漏。如果要同时关闭两者,则需要在资源块中为每个资源使用一条语句:
try (Connection connection = ds.getConnection();
PreparedStatement prepare = connection.prepareStatement(statement)) {
// your code here
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。