我写了一个方法来将外部 Mysql 数据作为学生 DAO 复制到我当前的数据库中。当我直接在持久层中写入当前数据库时,我得到了正确的结果,但是如果我返回一个列表以在逻辑层中使用它,就会发生奇怪的事情并且同名学生的“类(class)”字段是相同的它应该是不同的。
从数据库返回列表时,还有其他人遇到过奇怪的行为吗?
这是我的代码:
List<Student> fetchlist = new ArrayList<Student>();
try {
//Connecting to external DB
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection(dbstring);
//GET STUDENTS
Map<String, Student> studentMap = new HashMap<String, Student>();
Statement statementStudents = connect.createStatement();
ResultSet resultSetStudents = statementStudents.executeQuery("select * from students2");
while (resultSetStudents.next()) {
Student student = new Student();
String sid = resultSetStudents.getString("sid");
String firstname = resultSetStudents.getString("firstname");
String lastname = resultSetStudents.getString("lastname");
String email = resultSetStudents.getString("email");
student.setFirstname(StringEscapeUtils.unescapeHtml(firstname));
student.setName(StringEscapeUtils.unescapeHtml(lastname));
student.setEmail(email);
studentMap.put(sid, student);
}
Statement statementBookings = connect.createStatement();
ResultSet resultSetBookings = statementBookings.executeQuery("select * from bookings2");
//Go through bookings in order to complete Student and add
while (resultSetBookings.next()) {
String cid = resultSetBookings.getString("cid");
String sid = resultSetBookings.getString("sid");
String course = "";
if (cid.equals("1521"))
course = "Course 1";
else if (cid.equals("1522"))
course = "Course 2";
else if (cid.equals("1523"))
course = "Course 3";
else if (cid.equals("1524"))
course = "Course 4";
Student student = studentMap.get(sid);
student.setCourse(course);
fetchlist.add(student);
}
} catch (ClassNotFoundException e) {
log.error("Could not find Mysql JDBC class");
} catch (SQLException e) {
log.error("Error executing SQL statement");
}
return fetchlist;
最佳答案
为了添加列表,我创建了新的 Student 对象并用来自 HashMap 的对象的数据填充它们。我还尽可能关闭了所有语句和结果集。然后我在列表中没有任何错误的数据了。
关于java - 从 Mysql 数据库调用返回列表时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20534086/