简体   繁体   中英

Resultset.next returns true but doesn't return the value

I am trying to read from a mysql table and I am doing the following:

protected void pushRegisteredStudentsData() {
    try {
        conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
        stmt = conn.createStatement();

        String userID = "SELECT * FROM STUDENT";
        rs = stmt.executeQuery(userID);
        while (rs.next()) {
            int id = rs.getInt("ID");
            this.studentID = id;
            String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
                    + this.moduleCode + "')";
            System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
            stmt.executeUpdate(insertSql);
        }
    } catch (SQLException e) {

    }
}

..but for some reason,

while (rs.next()) {
    int id = rs.getInt("ID");

always returns the same ID , even though the table has different ID's on every line!

Does anyone have an idea why that might be? Thank you in advance! :(

EDIT: I was using a single statement to execute 2 updates, which was causing the problem!

It is a bit weird that it returns always the same value because it should only return the first value ONCE.

If you print the stacktrace instead of just catching the exception and doing nothing, you will see that it will print something like:

java.sql.SQLException: Operation not allowed after ResultSet closed
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
    at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)

You are using THE SAME statement for a Select and then for an Insert. This causes the resultSet that is "attached" to the Statement to close because it is not supposed to be used again.

It can be easily fixed by creating another statement:

        String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
                + this.moduleCode + "')";
        System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
        Statement stmt2 = conn.createStatement();
        stmt2.executeUpdate(insertSql);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM