我正在尝试从 mysql 表中读取数据,并且正在执行以下操作:
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) {
}
}
..但由于某种原因,
while (rs.next()) {
int id = rs.getInt("ID");
始终返回相同的 ID,即使表格每行具有不同的 ID!
有人知道为什么会这样吗? 先感谢您! :(
编辑: 我使用一条语句执行 2 个更新,这导致了问题!
最佳答案
它总是返回相同的值,这有点奇怪,因为它应该只返回第一个值一次。
如果您打印堆栈跟踪而不是仅仅捕获异常而不执行任何操作,您将看到它将打印如下内容:
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)
您正在使用相同的语句进行选择,然后进行插入。这会导致“附加”到 Statement 的 resultSet 关闭,因为不应再次使用它。
可以通过创建另一个语句轻松修复它:
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);
关于java - Resultset.next 返回 true 但不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33813592/