Skip to content

Commit dcd621f

Browse files
lbg-peteGitHub Enterprise
authored andcommitted
Merge pull request #1 from Software-Engineering-CoE/EC72-Java-Fix
Update EC72 Example Code
2 parents c1c55fe + 300337a commit dcd621f

File tree

1 file changed

+23
-14
lines changed
  • ecocode-rules-specifications/src/main/rules/EC72/java

1 file changed

+23
-14
lines changed

ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,23 +28,32 @@ public void foo() {
2828

2929
```java
3030
public void foo() {
31-
// ...
32-
String query = "SELECT name FROM users where id in (0 ";
33-
for (int i = 1; i < 20; i++) {
34-
35-
query = baseQuery.concat("," + i);
31+
StringBuilder queryBuilder = new StringBuilder("SELECT name FROM users WHERE id IN (");
32+
for (int i = 0; i < 20; i++) {
33+
if (i > 0) {
34+
queryBuilder.append(",");
35+
}
36+
queryBuilder.append("?");
3637
}
38+
queryBuilder.append(")");
39+
40+
String query = queryBuilder.toString();
3741

38-
query = baseQuery.concat(")");
39-
Statement st = conn.createStatement();
40-
ResultSet rs = st.executeQuery(query); // compliant
42+
try (Connection conn = DriverManager.getConnection("your-database-url");
43+
PreparedStatement pst = conn.prepareStatement(query)) {
4144

42-
// iterate through the java resultset
43-
while (rs.next()) {
44-
String name = rs.getString("name");
45-
System.out.println(name);
45+
for (int i = 0; i < 20; i++) {
46+
pst.setInt(i + 1, i);
47+
}
48+
49+
try (ResultSet rs = pst.executeQuery()) { // compliant
50+
while (rs.next()) {
51+
String name = rs.getString("name");
52+
System.out.println(name);
53+
}
54+
}
55+
} catch (SQLException e) {
56+
e.printStackTrace();
4657
}
47-
st.close();
48-
// ...
4958
}
5059
```

0 commit comments

Comments
 (0)