Why is this an issue?

Executing a batch of SQL queries instead of individual queries improves performance by reducing communication overhead with the database.

Batching SQL statements is beneficial in common situations where a SQL statement is executed within a loop. In such cases, adding the statement to a batch and subsequently executing it reduces the number of interactions with the database. This results in improved efficiency and faster execution times.

The rule raises an issue when it detects a java.sql.Statement being executed within a loop instruction, such as for, while or the forEach method of java.lang.Iterable, java.util.Map and java.util.stream.Stream.

How to fix it

Group SQL statements by using the method addBatch to add them to a batch and then execute them using executeBatch to send them to the database in a single call.

Code examples

Noncompliant code example

public void execute(Connection connection) {
  try {
    Statement statement = connection.createStatement();

    for (int i = 0; i < 10; i++) {
      statement.execute("INSERT INTO myTable (column1, column2) VALUES (" + i + ", 'value" + i + "')"); // Noncompliant
    }

    statement.close();
    connection.close();
  } catch (SQLException e) {
    e.printStackTrace();
  }
}

Compliant solution

public void execute(Connection connection) {
  try {
    Statement statement = connection.createStatement();

    for (int i = 0; i < 10; i++) {
      statement.addBatch("INSERT INTO myTable (column1, column2) VALUES (" + i + ", 'value" + i + "')"); // Compliant
    }
    statement.executeBatch();

    statement.close();
    connection.close();
  } catch (SQLException e) {
    e.printStackTrace();
  }
}

Resources

Documentation

Articles & blog posts