org.h2.jdbc.JdbcSQLException:对象已关闭

时间:2018-05-03 17:46:21

标签: java h2 resultset

对于我的生活,我看不出它“已经关闭”

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;


public class RsetTest2 {

    public static void main(String[] args) throws Exception {
        String dbpath = "jdbc:h2:c:/mydb;IFEXISTS=TRUE;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE";

        Connection conn = null;
        System.setProperty("h2.bindAddress", "127.0.0.1");
        Class.forName("org.h2.Driver");
        conn = DriverManager.getConnection(dbpath, "sa", "sa"); 
        conn.setAutoCommit(false);
        System.out.println("success.  querying database for latest values...");

        Statement qry = conn.createStatement();
        String sql = "select id from CONSTITUENTS where manager = 'abc' limit 1";                               
        ResultSet rset = qry.executeQuery(sql);
        while (rset.next()) {
            int id = rset.getInt("id");
            System.out.println(id);         
            qry.executeUpdate("insert into PAYREQUESTS (constituent, inblock) values (" + id + ", 238)");
        }
        rset.close();
        qry.close();    
    }
}

这是输出:

success.  querying database for latest values...
103
Exception in thread "main" org.h2.jdbc.JdbcSQLException: The object is already closed [90007-196]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.message.DbException.get(DbException.java:144)
    at org.h2.jdbc.JdbcResultSet.checkClosed(JdbcResultSet.java:3208)
    at org.h2.jdbc.JdbcResultSet.next(JdbcResultSet.java:130)
    at RsetTest2.main(RsetTest2.java:22)

其中22对应于“while(rset.next()){”line

DB正在返回值,请参阅给我们103的println语句。

甚至更奇怪,如果我//注释掉executeUpdate行,它都会正常完成

1 个答案:

答案 0 :(得分:3)

  

线程“main”中的异常org.h2.jdbc.JdbcSQLException:对象已经关闭[90007-196]

您的问题是您正在重用Statement循环内的SQL while。只要在循环中调用qry.executeUpdate(...)方法,就会关闭与前一个语句关联的ResultSet rset,从而导致错误。在循环中的第一个while(rset.next())失败后,executeUpdate(...)语句被称为

如果你在循环中使用 new 语句,它应该可以工作。

Statement qry = conn.createStatement();
String sql = "select id from CONSTITUENTS where manager = 'abc' limit 1";
ResultSet rset = qry.executeQuery(sql);
while (rset.next()) {
    int id = rset.getInt("id");
    System.out.println(id);
    // we can't reuse the same Statement here so we need to create a new one
    conn.createStatement().executeUpdate("insert into PAYREQUESTS ...");
}

您可以考虑保留必要更新的集合,然后在循环结束时发布更新。

  

甚至更奇怪,如果我//注释掉executeUpdate行,它都会正常完成

是的,这听起来不错。一点儿都不奇怪。 : - )