gpt4 book ai didi

java - PreparedStatement 和 ResultSet 上的资源泄漏

转载 作者:行者123 更新时间:2023-12-01 07:18:46 25 4
gpt4 key购买 nike

Eclipse 显示警告消息“资源泄漏,准备好的语句未在以下位置关闭”

对我来说,finally block 似乎负责关闭准备好的语句和 rs 对象。知道为什么 eclipse 仍然提示资源泄漏吗?

String ruleGrpId = null;
int finalRuleID = 0;

String saveRule1 = "INSERT INTO ..";
String saveRule2 = "INSERT INTO ";

String saveRule3 = "select ..._name = ?";

PreparedStatement preparedstatement = null;
ResultSet rs = null;

try {
if (objSomeRule.getRule() == 0) {

preparedstatement = con.prepareStatement(saveRule1);
preparedstatement.setString(1, ruleId);

preparedstatement.executeUpdate();

//Eclipse complains here
preparedstatement = con.prepareStatement(saveRule2);

preparedstatement.setInt(1, ruleID_2);
preparedstatement.setString(2, ruleID_3);

rs = preparedstatement.executeQuery();

if(rs.next()){
finalRuleID = rs.getInt(1);
}else{
//complains here
preparedstatement = con.prepareStatement(saveRule3);
preparedstatement.setString(1, ruleID_4);
//complains here
rs = preparedstatement.executeQuery();
if(rs.next()){
finalRuleID = rs.getInt("rulegroup_id");
}
}
objSomeRule.setRuleID(finalRuleID);

}

} finally {

if(preparedstatement != null){
preparedstatement.close();
}

if(rs != null){
rs.close();
}
}

return finalRuleID;
}

最佳答案

重用变量preparedStatementrs可以防止对变量的旧对象值调用close()。 Try-with-resources 是一个巧妙的解决方案,因为即使抛出异常或在深度嵌套的 try 中执行返回,也会自动调用 close()

    String ruleGrpId = null;
int finalRuleID = 0;
String saveRule1 = "INSERT INTO ..";
String saveRule2 = "INSERT INTO ";
String saveRule3 = "select ..._name = ?";

if (objSomeRule.getRule() == 0) {
try (PreparedStatement ps1 = con.prepareStatement(saveRule1)) {
ps1.setString(1, ruleId);
ps1.executeUpdate();
}
try (PreparedStatement ps2 = con.prepareStatement(saveRule2)) {
ps2.setInt(1, ruleID_2);
ps2.setString(2, ruleID_3);

try (ResultSet rs2 = ps2.executeQuery()) {

if (rs2.next()) {
finalRuleID = rs2.getInt(1);
} else {
try (Preparedstatement ps3 = con.prepareStatement(saveRule3)) {
ps3.setString(1, ruleID_4);
//complains here
try (ResultSet rs3 = ps3.executeQuery()) {
if (rs3.next()) {
finalRuleID = rs3.getInt("rulegroup_id");
}
}
}
}
}
objSomeRule.setRuleID(finalRuleID);
}
}

如果最后一个 SELECT 查询打算检索先前 INSERT 的 AUTOINCRMENT ID,则可以使用 getGeneratedKeys 更安全(多用户)和更好地完成此操作。

关于java - PreparedStatement 和 ResultSet 上的资源泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48305665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com