0

标题:Java - SonarLint Detect the Blocker - 在“finally”子句中关闭此“PreparedStatement”。

问题:我在一个方法中有多个 PreparedStatement(示例),然后我已经关闭 PreparedStatement 但 PreparedStatement 的第一行(//preparedStatement no 1 - table_a)仍然检测到 Blocker -(在“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);
        }
    }
4

1 回答 1

1

您没有关闭准备好的语句。您只关闭最后一个(或发生异常的第一个)。所有其他人都没有关闭。仅仅因为您将它们分配给相同的局部变量 ( preparedStatement) 并不意味着Connection.prepareStatement重用前面的语句。事实上,我怀疑它确实如此,毕竟它不知道你的代码是怎么做的。

要确认,请在调试器中查看您的代码。密切注意准备好的语句的数量及其内部结构。

您最好的选择是使用try with resources在超出范围时自动关闭每个语句。

于 2018-07-06T08:00:44.010 回答