A JDBC statement is prepared again on every pass of a loop

tx0/java:repeated-statement-preparationrecommendedwarningperformance

What it finds

connection.prepareStatement(sql) inside a loop sends the statement to the database to be parsed and planned on every pass. Preparing it once before the loop and only setting its parameters inside is what prepared statements are for.

Reported is prepareStatement or prepareCall inside a loop of the same body.

From the rule's source, statement_prepared_in_loop.rs.

Example from the rule's tests
import java.sql.Connection;import java.sql.PreparedStatement;import java.util.List; class Batch {  void save(Connection connection, List<String> names) throws Exception {    for (String name : names) {      PreparedStatement statement = connection.prepareStatement("insert into t values (?)");tx0 reports: prepared again on every pass      statement.setString(1, name);    }  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:repeated-statement-preparation" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:repeated-statement-preparation] reason="..."

tx0 explain tx0/java:repeated-statement-preparation shows the same in the terminal. Found a false positive? Report it.