I am trying to save my Database Table in a ListArray of a Class Students.
public List<Students> getData() {
//_Students.clear();
Students tempStudent = new Students();
List<Students> students = new ArrayList<>();
dbConnect();
try {
stmt = c.createStatement();
rs = stmt.executeQuery("SELECT * FROM Students;");
int size = 0;
while (rs.next()) {
tempStudent.studentId = rs.getInt("StudentNo");
tempStudent.studentName = rs.getString("StudentName");
tempStudent.studentAge = rs.getInt("StudentAge");
students.add(tempStudent);
size++;
}
rs.close();
c.commit();
stmt.close();
c.close();
} catch (SQLException e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
return students;
}
In while loop when i try to print data as
System.out.println("Student Id: " + tempStudent.studentId);
it prints perfectly fine. But when i try to print it as
for (int i = 0; i < size; i++) {
System.out.println("Student Id: " + student.get(i).studentId);
}
It prints the last record that was read from Database. Number of records is same. If there are 4 rows saved in Database table then the record that is displayed will also be 4 times.
Is there something wrong with the way i am using LIST? Thanks!
Students tempStudent = new Students();
change it to
Students tempStudent;
You are overridding
the property of same object
since you created the tempStudent
outside
the while loop
. You have to add the objects
equal to the number of record
in the database. So create the tempStudent object
as below.
use
while (rs.next()) {
tempStudent = new Students();
tempStudent.studentId = rs.getInt("StudentNo");
tempStudent.studentName = rs.getString("StudentName");
tempStudent.studentAge = rs.getInt("StudentAge");
students.add(tempStudent);
size++;
}
Create a new Object in every iteration that will resolve your problem.
tempStudent = new Students();
tempStudent.studentId = rs.getInt("StudentNo");
tempStudent.studentName = rs.getString("StudentName");
tempStudent.studentAge = rs.getInt("StudentAge");
students.add(tempStudent);
size++;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With