0

我有一个有两个字符串列表的类。

public class School {
private List<String> students;
private List<String> teachers;
//getters and setters
}

我的 DAO 类中有以下方法,其中填充了学校对象。

public static School fetchSchoolInfo(String schoolName) throws SQLException
{       
    School school = null;
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet rs = null;
    List<String> students = new ArrayList<String>();
    List<String> teachers = new ArrayList<String>();        
    try {
        connection = createConnection();
        statement = connection.prepareStatement("SELECT COL_STUDENT,COL_TEACHERS FROM SCHOOL WHERE SCHOOLNAME=?");
        statement.setString(1, schoolName);
        rs = statement.executeQuery();
        while(rs.next())
        {
            school = new School();                              
            students.add(rs.getString(1));
            teachers.add(rs.getString(1));
            school.setStudents(students);
            school.setTeachers(teachers);               
        }                       
    } finally{
        rs.close();
        statement.close();
        connection.close();
    }

    return school;
}

现在,如果我这样做,

School school = MyDAO.fetchPersonDeviceIdInfo("SJSU");
System.out.println(school);

学校对象会拥有 SJSU 的所有信息吗?我知道我可以自己尝试并检查一下,但是我的应用程序非常复杂,并且需要一段时间才能将此代码与我的应用程序集成。请建议。另外,我需要一个字符串吗?

非常感谢!

4

2 回答 2

5

更改以下内容:

while(rs.next())
    {
        school = new School();                              
        students.add(rs.getString(1));
        teachers.add(rs.getString(1));
        school.setStudents(students);
        school.setTeachers(teachers);               
    }  

school = new School(); 
while(rs.next())
    {

        students.add(rs.getString(1));
        teachers.add(rs.getString(2)); // changed

    }  

school.setStudents(students);
school.setTeachers(teachers);  
于 2013-10-22T05:41:20.277 回答
1

像这样覆盖你的School.toString()方法

class School {
  private List<String> students;
  private List<String> teachers;
  @Override
  public String toString() {
      return "School [students=" + students + ", teachers=" + teachers + "]";
  } 
}

那你试试

School school = MyDAO.fetchPersonDeviceIdInfo("SJSU");
System.out.println(school);
于 2013-10-22T05:43:13.850 回答