0

I'm trying to create a for cycle with a dynamic sql statement:

for(int i = 0; i < size; i++) {         
            ps2 = db.prepareStatement("select * from student where id=?");
            ps2.setInt(1,studList[i]);
            rs2=ps2.executeQuery();
            while(rs2.next()){
                list1.add(new Student(rs2.getInt("id"), rs2.getString("name"), rs2.getString("city"));
            }
            rs2.close();
            ps2.close();
        }

studList[i] is an array with all the student ID and the variable "size" is the length of this array. The problem with this code is that only one element is added to the list(corresponding to the first student ID). I noticed that the code goes inside 'while(rs2.next())' just if the value of studList[i] doesn't change. Why?

Rudy
  • 33
  • 4

1 Answers1

3

Seemingly the logic is fine.

First the code would be better with

  • local declarations at the first usage, otherwise ps2, rs2, ps3, rs3 and so one risk undetected typos;
  • try-with-resources that close even on exception/return.

So:

String sql = "select name, city from student where id=?";
try (PreparedStatement ps2 = db.prepareStatement(sql)) {
    for (int i = 0; i < size; i++) {  
        int id = studList[i];
        ps2.setInt(1, id);
        try (ResultSet rs2 = ps2.executeQuery()) {
            System.out.printf("[%d] %d%n", i, id);
            while (rs2.next()) {
                System.out.printf("- %s%n", rs2.getString("name"));
                list1.add(new Student(id, rs2.getString("name"), rs2.getString("city"));
            }
        }
    }
}

So the error might happen before: the array filled false, the database student table corrupted.

One beginner error is to reuse an object (Student), with new field values. Adding the same object to a list then would have the last student's data replicated several times.

Here it could be that in the original code code was called reusing ps2 or such.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138