我目前正在尝试使用JDBC从我的数据库中删除项目,但是我收到的错误是我无法弄清楚如何逃脱。错误是:
Caused by: java.sql.SQLException: Operation not allowed after ResultSet closed
这是java:
System.out.println("Connecting database for Delete...");
Integer deletedCount = 0;
Statement deleteStatement = null;
try (Connection conn = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
deleteStatement = conn.createStatement();
String selectDelete = "SELECT id FROM table WHERE end <= (NOW() - INTERVAL 1 HOUR)";
ResultSet rs = deleteStatement.executeQuery(selectDelete);
while (rs.next()) {
String eventid = rs.getString("id");
String deleteSQL = "DELETE FROM table WHERE id = " + eventid;
deleteStatement.executeUpdate(deleteSQL);
deletedCount++;
System.out.println(deletedCount);
}
System.out.println("Completed Delete! "+ deletedCount +" deleted!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
我在这里做的是首先选择已经过去的所有项目并将其设置为结果集。然后我通过while循环尝试从数据库中删除它们。它运行一次并得到我将完全放在下面的错误。每次循环时我都需要创建一个新的删除语句吗?我无法想办法正确地做到这一点。
以下是完整错误:
Connecting database for Delete...
Database connected!
1
Exception in thread "main" java.lang.IllegalStateException: Cannot connect the database!
at JDBC.deleteOverDueEvents(JDBC.java:56)
at EventJSON.main(EventJSON.java:31)
Caused by: java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:963)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:743)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6313)
at JDBC.deleteOverDueEvents(JDBC.java:45)
... 1 more
答案 0 :(得分:2)
时为什么选择SELECT,LOOP和DELETE
String deleteSQL= "DELETE FROM table WHERE end <= (NOW() - INTERVAL 1 HOUR)";
Statement deleteStatement = conn.createStatement();
deleteStatement.executeUpdate(deleteSQL);
可以更有效地工作
答案 1 :(得分:1)
当行
deleteStatement.executeUpdate(deleteSQL);
执行,然后ResultSet rs
自动closed:
当Statement对象时,ResultSet对象自动关闭 生成它的是关闭,重新执行或用于检索下一个 由多个结果序列产生。
但你可以通过运行
来解决这个问题String deleteCmd = "DELETE FROM table WHERE end <= (NOW() - INTERVAL 1 HOUR)";
int deletedCount = deleteStatement.executeUpdate(deleteCmd);
而不是选择记录并删除它们。
答案 2 :(得分:0)
我认为这种情况正在发生,因为您在循环到结果集时删除了行并且您的逻辑完全错误。您使用&#34;结束&lt; =(NOW() - INTERVAL 1 HOUR)&#34;选择所有ID然后删除它。为什么不首先删除所有内容?像这样&#34; DELETE FROM表WHERE end&lt; =(NOW() - INTERVAL 1 HOUR)&#34;。如果您需要先将计数转到select语句,然后再转到删除查询。