Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListArray Saving Same records

Tags:

java

sql

list

mysql

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!

like image 928
Muneeb Mirza Avatar asked Dec 11 '22 07:12

Muneeb Mirza


2 Answers

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++;
    }
like image 63
Rahul Avatar answered Jan 19 '23 17:01

Rahul


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++;
like image 21
newuser Avatar answered Jan 19 '23 19:01

newuser