我试图将数据库表保存在班级 学生* 的 ListArray 中。 *
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; }
在while循环中,当我尝试将数据打印为
System.out.println("Student Id: " + tempStudent.studentId);
它打印完美。但是当我尝试将其打印为
for (int i = 0; i < size; i++) { System.out.println("Student Id: " + student.get(i).studentId); }
它打印从数据库读取的最后一条记录。记录数相同。如果在数据库表中保存了4行,那么显示的记录也将是4次。
我使用LIST的方式有问题吗?谢谢!
Students tempStudent = new Students();
更改为
Students tempStudent;
您是overridding,property of same object因为您创建tempStudent outside了while loop。您必须在数据库中添加objects等于number of record。因此,创建tempStudent object如下。
overridding
property of same object
tempStudent
outside
while loop
objects
number of record
tempStudent object
使用
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++; }