标题:Java-SonarLint检测到阻止程序-在“ finally”子句中关闭此“ PreparedStatement”。
问题:我在一个方法中有多个PreparedStatement(示例),然后我关闭了PreparedStatement,但是 PreparedStatement的第一行(// prepareStatement否1-table_a)仍检测到阻止程序-(在“ finally”子句中关闭此“ PreparedStatement”):
PreparedStatement preparedStatement = null;
try {
connection.setAutoCommit(false);
// prepareStatement no 1
preparedStatement = connection.prepareStatement("delete from table_a where abc_id=?");
preparedStatement.setString(1, abc_id);
preparedStatement.executeUpdate();
// prepareStatement no 2
preparedStatement = connection.prepareStatement("delete from table_b where bc_id=?");
preparedStatement.setString(1, bc_id);
preparedStatement.executeUpdate();
// prepareStatement no 3
preparedStatement = connection.prepareStatement("delete from table_c where cd_id=?");
preparedStatement.setString(1, cd_id);
preparedStatement.executeUpdate();
// prepareStatement no 4
preparedStatement = connection.prepareStatement("delete from table_d where de_id=?");
preparedStatement.setString(1, de_id);
preparedStatement.executeUpdate();
// prepareStatement no 5
preparedStatement = connection.prepareStatement("delete from table_e where ef_id=?");
preparedStatement.setString(1, ef_id);
preparedStatement.executeUpdate();
// prepareStatement no 6
preparedStatement = connection.prepareStatement("delete from table_f where fg_id=?");
preparedStatement.setString(1, fg_id);
preparedStatement.executeUpdate();
connection.commit();
} catch(SQLException e) {
log.error(e);
} finally {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
connection.setAutoCommit(true);
} catch (SQLException e) {
log.error(e);
}
}
答案 0 :(得分:1)
您没有关闭准备好的语句。您仅关闭最后一个(或发生异常的第一个)。其他所有都未公开。仅仅因为将它们分配给相同的局部变量(preparedStatement
)并不意味着Connection.prepareStatement
重用了前面的语句。实际上,我怀疑它会这样做,毕竟它不知道您的代码是怎么做的。
要确认,请在调试器中观看代码。密切注意准备好的语句的数量及其内部。
您最好的选择是使用try with resources在超出范围时自动关闭每个语句。