在 "finally" 子句中使用 try-with-resources/close 这个 "PreparedStatement"

Use try-with-resources/close this "PreparedStatement" in a "finally" clause

我是 运行 我的 JDBC sonarqube 代码。我的代码有问题。

try (final Connection connection = DatabaseConnectionProvider.createConnection(configuration)) {
        PreparedStatement statement = connection.prepareStatement(
                "SELECT 1 FROM `todo_items` WHERE `id` = ? LIMIT 1;");
        statement.setLong(1, id);
        ResultSet resultSet = statement.executeQuery();
        if (!resultSet.next()) {
            return false;
        }
        statement = connection.prepareStatement("UPDATE `todo_items` SET `checked` = ? WHERE id = ?;");
        statement.setBoolean(1, checked);
        statement.setLong(2, id);
        statement.executeUpdate();
        return true;
    }

它说第 3 行和第 9 行存在阻塞问题。

“使用 try-with-resources 或在“finally”子句中关闭此“PreparedStatement”。”我不明白这个。

您可以使用内部 try-with-resources,因为您在内部有 2 个不同的准备语句:

try (final Connection connection = DatabaseConnectionProvider.createConnection(configuration)) {
    try(PreparedStatement statement = connection.prepareStatement("SELECT 1 FROM `todo_items` WHERE `id` = ? LIMIT 1;")) {
        statement.setLong(1, id);
        ResultSet resultSet = statement.executeQuery();
        if (!resultSet.next()) {
            return false;
        }
    }
    try(PreparedStatement statement = connection.prepareStatement("UPDATE `todo_items` SET `checked` = ? WHERE id = ?;")) {
        statement.setBoolean(1, checked);
        statement.setLong(2, id);
        statement.executeUpdate();
        return true;
    }
}

可以进行小的优化(请注意 try(.....) 中存在 2 Autoclosable

try (final Connection connection = DatabaseConnectionProvider.createConnection(configuration);
        PreparedStatement statement = connection.prepareStatement("UPDATE `todo_items` SET `checked` = ? WHERE id = ?;")) {
    statement.setBoolean(1, checked);
    statement.setLong(2, id);
    return statement.executeUpdate() > 0;
}

您不必查询数据库中的行是否存在,因为更新的行数通常由 executeUpdate() 编辑 return。实际 return 值可能 JDBC 驱动程序实现依赖(尽管 JDBC 规范对此非常清楚)。