【问题标题】:Operation not allowed after ResultSet closedResultSet 关闭后不允许操作
【发布时间】:2012-06-11 14:25:43
【问题描述】:

好吧,过去 2 天一直在尝试解决这个问题。

Statement statement = con.createStatement();
                        String query = "SELECT * FROM sell";
                        ResultSet rs = query(query);
                        while (rs.next()){//<--- I get there operation error here

这是查询方法。

    public static ResultSet query(String s) throws SQLException {
        try {
            if (s.toLowerCase().startsWith("select")) {
                if(stm == null) {
                    createConnection();
                }
                ResultSet rs = stm.executeQuery(s);
                return rs;
            } else {
                if(stm == null) {
                    createConnection();
                }
                stm.executeUpdate(s);
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            con = null;
            stm = null;
        }
        return null;
    }

我该如何解决这个错误?

【问题讨论】:

  • 您的应用程序中还有其他线程吗?
  • 如果您发布您遇到的实际错误会很有用。如果没有对正在发生的事情的描述,人们无法真正帮助解决问题。我也看不到您在“查询”方法中创建连接或语句的位置。我看到一个对 createConnection() 的调用,但那里没有分配,也没有在该方法中分配“stm”。

标签: java sql select resultset


【解决方案1】:

仅从您发布的代码中很难确定,但我怀疑ResultSet 无意中被关闭(或stm 被重用)while 循环的主体内。这将在下一次迭代开始时触发异常。

此外,您需要确保您的应用程序中没有其他线程可能使用相同的数据库连接或stm 对象。

【讨论】:

  • 值得。代码写得很脏,写得不必要的复杂。
【解决方案2】:

恕我直言,在关闭连接之前,您应该使用 ResultSet 完成所需的一切。

【讨论】:

    【解决方案3】:

    您需要解决的问题很少。打开连接、运行查询以获取 rs、关闭连接以及关闭连接都应尽可能在同一函数范围内完成。从您的代码中,您似乎将“con”变量用作全局变量,这可能会导致问题。你没有关闭 stm 对象。或 rs 对象。这段代码不会运行太久,即使它没有错误。你的代码应该是这样的:

    if (stringUtils.isBlank(sql)){
         throw new IllegalArgumentsException ("SQL statement is required");
    }
    Connection con = null;
    PreparedStatement ps =null;
    Resultset rs = null;
    try{
             con = getConnection();
             ps = con.preparestatement(sql);
             rs = ps.executeQuery();
             processResults(rs);
             close(rs);
             close(ps);
             close(con);
    }catch (Execption e){
            log.Exception ("Error in: {}", sql, e);
            throw new RuntimeException (e);
    }finally{
            close(rs);
            close(ps);
            close(con);
    }
    

    【讨论】:

      【解决方案4】:

      在内循环中使用另一个 Statement 对象 喜欢

      Statement st,st1;
      
      st=con.createStatement();
      st1=con.createStatement();
      
      //in Inner loop
      while(<<your code>>)
      {
         st1.executeQuery(<<your query>>);
      }
      

      【讨论】:

        【解决方案5】:

        我知道这已经晚了几年,但我发现同步 db 方法通常可以解决这个问题。

        【讨论】:

          猜你喜欢
          • 2017-04-17
          • 2018-03-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多