From 300337a3e2ae526efeb8e9d916b5c567ad63b404 Mon Sep 17 00:00:00 2001 From: "McCorrie, Peter (Software Engineering CoE)" Date: Fri, 8 Nov 2024 13:56:25 +0000 Subject: [PATCH] Update EC72 Example Code The EC72 example compliant code doesn't compile and breaks other SonarQube rules that prevent introducing vulnerability to SQL Injection. This example complaint code conforms to other SonarQube rules, correctly compiles and still results in the efficiency saving that the rule is intended to give. --- .../src/main/rules/EC72/java/EC72.asciidoc | 37 ++++++++++++------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc b/ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc index 7032eb960..0299a56e4 100644 --- a/ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc @@ -28,23 +28,32 @@ public void foo() { ```java public void foo() { - // ... - String query = "SELECT name FROM users where id in (0 "; - for (int i = 1; i < 20; i++) { - - query = baseQuery.concat("," + i); + StringBuilder queryBuilder = new StringBuilder("SELECT name FROM users WHERE id IN ("); + for (int i = 0; i < 20; i++) { + if (i > 0) { + queryBuilder.append(","); + } + queryBuilder.append("?"); } + queryBuilder.append(")"); + + String query = queryBuilder.toString(); - query = baseQuery.concat(")"); - Statement st = conn.createStatement(); - ResultSet rs = st.executeQuery(query); // compliant + try (Connection conn = DriverManager.getConnection("your-database-url"); + PreparedStatement pst = conn.prepareStatement(query)) { - // iterate through the java resultset - while (rs.next()) { - String name = rs.getString("name"); - System.out.println(name); + for (int i = 0; i < 20; i++) { + pst.setInt(i + 1, i); + } + + try (ResultSet rs = pst.executeQuery()) { // compliant + while (rs.next()) { + String name = rs.getString("name"); + System.out.println(name); + } + } + } catch (SQLException e) { + e.printStackTrace(); } - st.close(); - // ... } ```