我正在用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);
}
我得到一个例外说法:"资源泄漏:' stat'没有在这个位置关闭"在 else 块中。我该如何重构呢?
提前谢谢
答案 0 :(得分:1)
应始终在JDBC中显式关闭PreparedStatements。使用PreparedStatement的一般模式是:
从Java 7开始,确保始终正确执行此操作的最简单方法是在try with resources块中使用该语句。
答案 1 :(得分:1)
使用单独的变量,绝对是试用资源。
try (PreparedStatement prepStat =
connection.prepareStatement("some SQL stuff");
ResultSet result = prepStat.executeQuery()) {
...
try (PreparedStatement prepStat2 =
connection.prepareStatement(condition2 ? "some SQL stuff" : "some SQL stuff") {
try (ResultSet result2 = prepStat.executeQuery();
// Use of result2
}
}
}
然后一切都很好地关闭,即使有异常或返回声明。
答案 2 :(得分:0)
在重新使用之前,您还没有关闭prepStat。还尝试关闭finally块中的语句而不是尝试,因为它可能会留下未关闭的可关闭语句。
if (condition1){
prepStat = connection.prepareStatement("some SQL stuff");
result = prepStat.executeQuery();
// Another use of result
prepStat.close(); //close the statement
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();
}