我正在用 Java 编写一段涉及数据库 (SQLite) 的代码,而且我是新手,所以我需要这方面的帮助。 我的代码如下所示:
Connection connection = null;
try {
connection = SQLiteConnector.getConnection(database Name);
PreparedStatement prepStat = connection.prepareStatement("some SQL stuff");
ResultSet result= prepStat.executeQuery();
// Use of result
if (condition1){
prepStat = connection.prepareStatement("some SQL stuff");
result = prepStat.executeQuery();
// Another use of result
if (condition2){
prepStat = connection.prepareStatement("some SQL stuff");
}
else{
prepStat = connection.prepareStatement("some SQL stuff");
}
result = prepStat.executeQuery();
// Use of result
result.close();
prepStat.close();
}
} catch (Exception e) {
// Exception management
}
finally{
SQLiteConnector.closeConnection(connection);
}
我在 else block 中收到一条异常消息:“资源泄漏:'stat' 在此位置未关闭”。我该如何重构它?
提前谢谢
最佳答案
PreparedStatements 应始终在 JDBC 中显式关闭。使用PreparedStatement 的一般模式是:
- 创建声明。
- 设置参数并执行。
- 设置不同的参数并执行。
- 设置更多参数并执行。
- 结束语句。
从 Java 7 开始,确保始终正确执行此操作的最简单方法是在 try with resources 中使用该语句。 block 。
关于PreparedStatement 中的 Java 资源泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26420853/