Invalid state, the ResultSet object is closed

2019-02-18 18:09发布

I am running the code, however am getting a "Invalid state, the ResultSet object is closed." error. What is causing the error?

try{
    query = "SELECT * FROM BUNDLE_TEMP "
                  + "MINUS "
                  + "SELECT * FROM BUNDLE";

            rs = stmt.executeQuery(query);

            while (rs.next()){
                String bundle = rs.getString("BUNDLE");
                String week = rs.getString("WEEK");
                String sched_dt = rs.getString("SCHED_DT").replace(" 00:00:00.0", "");
                String dropper_id = rs.getString("DROPPER_ID");


                query = "INSERT INTO BUNDLE "
                            + "VALUES ('"
                                + bundle+"','"
                                + week+"','"
                                + sched_dt+"','"
                                + dropper_id+"')";

                stmt.executeUpdate(query);
            }
        }catch(Exception e){
            System.out.println("Error while trying to insert into BUNDLE\n"+query+"\n"+ e);
        }

1条回答
姐就是有狂的资本
2楼-- · 2019-02-18 19:02

You cannot execute another SQL query on the same Statement you're currently iterating over with a ResultSet. Doing this will close the previously open cursor (your SELECT query resp. ResultSet):

To quote the API docs for Statement:

By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

Create another Statement instance from your Connection, let's call it updateStmt and executeUpdate() on that one.

Also, look into Prepared Statements for your update, it will probably be more performant and secure.

查看更多
登录 后发表回答