The java.sql.PreparedStatement represents a precompiled SQL statement that can be efficiently executed multiple times.
The PreparedStatement is frequently used in loops because it allows to conveniently set parameters. A small optimization is possible
by setting constant parameters outside the loop or hard-coding them in the query whenever possible.
Place calls to setter methods that take a constant argument outside the loop.
public class DatabaseExample {
public record Order(String id, BigDecimal price) {}
public void updateTodayOrders(Connection connection, List<Order> orders) {
Date today = java.sql.Date.valueOf(LocalDate.now());
String insertQuery = "INSERT INTO Order (id, price, executionDate) VALUES (?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
for(Order order: orders) {
preparedStatement.setString(1, order.id());
preparedStatement.setString(2, order.price());
preparedStatement.setDate(3, today); // Noncompliant
preparedStatement.executeUpdate();
}
}
}
public class DatabaseExample {
public record Order(String id, BigDecimal price) {}
public void updateTodayOrders(Connection connection, List<Order> orders) {
Date today = java.sql.Date.valueOf(LocalDate.now());
String insertQuery = "INSERT INTO Order (id, price, executionDate) VALUES (?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
preparedStatement.setDate(3, today); // Compliant
for(Order order: orders) {
preparedStatement.setString(1, order.id());
preparedStatement.setString(2, order.price());
preparedStatement.executeUpdate();
}
}
}