Operation not allowed after ResultSet closed解决方法

出现下面的报错:

java.sql.SQLException: Operation not allowed after ResultSet closed
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
	at com.mysql.cj.jdbc.result.ResultSetImpl.checkClosed(ResultSetImpl.java:445)
	at com.mysql.cj.jdbc.result.ResultSetImpl.next(ResultSetImpl.java:1726)

部分原代码如下:

private void execute(){
        try(Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/BMS?serverTimezone=GMT%2B8","3219003920","lxhd")) {
            Statement statement = con.createStatement();
            statement.execute("begin;");
            String sql="select id from Reader where id=" + this.reader.getid();
            ResultSet ls =statement.executeQuery(sql);
            while (ls.next()){
                statement.executeUpdate("delete from Reader where id=" + this.reader.getid());
                complete = true;
            }
            statement.execute("commit;");
        } catch(Exception e1) {
            e1.printStackTrace();
        }
    }

通过网上查找资料发现主要因为每执行一次execue操作ls就会被自动地关闭。而对一个已经关闭的ls再执行next显然是错误的。因此在while语句里面添加,这样在每次用到statement的时候都创建一个新的Statement对象。这样就不会重复的使用ls了。

statement = con.createStatement();

修改代码如下:

private void execute(){
        try(Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/BMS?serverTimezone=GMT%2B8","3219003920","lxhd")) {
            Statement statement = con.createStatement();
            statement.execute("begin;");
            String sql="select id from Reader where id=" + this.reader.getid();
            ResultSet ls =statement.executeQuery(sql);
            while (ls.next()){
                statement = con.createStatement();
                statement.executeUpdate("delete from Reader where id=" + this.reader.getid());
                complete = true;
            }
            statement.execute("commit;");
        } catch(Exception e1) {
            e1.printStackTrace();
        }
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值