从Mysql数据库调用返回列表时的奇怪行为

时间:2013-12-12 02:46:38

标签: java mysql

我写了一个方法将外部Mysql数据作为Student DAO复制到我当前的数据库中。当我直接在持久层中写入当前数据库时,我得到了正确的结果,但是如果我返回一个列表以在逻辑层中使用它,那么奇怪的事情发生了,并且同名学生的“courses”字段是相同的应该是不同的。

从数据库返回列表时,其他任何人都遇到过奇怪的行为吗?

这是我的代码:

    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;

1 个答案:

答案 0 :(得分:0)

对于列表添加,我创建了新的Student对象,并用来自HashMap的对象中的数据填充它们。我还尽可能关闭了所有的陈述和结果集。然后我在列表中没有任何错误的数据。