我有一个有两个字符串列表的类。
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的所有信息?我知道理想情况下我可以自己尝试并检查,但我的应用程序非常复杂,并且需要一段时间才能将此代码与我的应用程序集成。请建议。另外,我需要一个字符串吗?
非常感谢!
答案 0 :(得分: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);
答案 1 :(得分: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);