【发布时间】:2021-03-20 12:32:43
【问题描述】:
我在 sonarqube 上运行我的 JDBC 代码。我的代码有问题。
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-resource用于连接。把准备好的语句也放在那里。 -
如果你尝试 JdbcTemplate,你可以用更少的样板更简单地解决这个问题。您已经在使用 Spring。为什么你不使用那个类对我来说是个谜。您应该在启动时将数据源池化并在 Spring bean 工厂中实例化池。