Executing SQL queries in loop induced unnecessary calculation by the CPU, RAM usage and network transfer.

Noncompliant Code Example

public void foo() {
    // ...
    String baseQuery = "SELECT name FROM users where id = ";

    for (int i = 0; i < 20; i++) {

        String query  = baseQuery.concat("" + i);
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery(query); // Noncompliant

        // iterate through the java resultset
        while (rs.next()) {
            String name = rs.getString("name");
            System.out.println(name);
        }
        st.close();
    }
    // ...
}

Compliant Solution

public void foo() {
    // ...
    String query = "SELECT name FROM users where id in (0 ";
    for (int i = 1; i < 20; i++) {

        query  = baseQuery.concat("," + i);
    }

    query  = baseQuery.concat(")");
    Statement st = conn.createStatement();
    ResultSet rs = st.executeQuery(query); // compliant

    // iterate through the java resultset
    while (rs.next()) {
        String name = rs.getString("name");
        System.out.println(name);
    }
    st.close();
    // ...
}