1
try{
      String query= "select user_name from user";
      ResultSet rs = queries.performQuery(query);

while(rs.next()){
        System.out.println("User Name :" + rs.getString("user_name"));
      }

在另一堂课上,我有这样的事情:

public ResultSet performQuery(String query) throws SQLException
    {       
        try 
        {
              connection = DriverManager.getConnection(sqlUrl,sqlUser,sqlPassword);
              stmt = connection.createStatement();
                  rs = stmt.executeQuery(query);
        } 

        catch(SQLException ex) 
        {
        }

        finally{
            close(rs);
            close(stmt);
            close(connection);
        }
        return rs;
    }

现在我在 ResultSet 关闭后得到错误 Operation not allowed ,这显然是因为我正在关闭 rs/stmt/connection。

我没有我的代码,所以这只是我的想法,忽略任何语法错误,我希望我的问题仍然足够清楚。

所以我的问题是:

如果您想要一个方法来执行查询,并且您在另一个方法中调用它然后执行 rs.next,那么关闭结果集/stmt/connection 的适当方法是什么?对我来说,关闭它们的 performQuery 是有意义的,但这给了我错误。

4

2 回答 2

2

if you are using ResultSet then it will need the Connection to load more rows . for example if your query returns 1000 record , first the ResultSet will hold 41 row in memory then when you iterate over this number it will use the Connection to load another chuck of records .in your case i would use RowSet for more explanation read this

于 2012-04-15T18:58:04.337 回答
1

ResultSet is designed to allow streaming of results, e.g. one record at a time. That's why it is not simply returning a Collection of some kind but rather something similar to iterator. In fact ResultSet can lazily load one record at a time through open JDBC connection.

That being said if you are comfortable with having all the results in memory at the same time - just eagerly load all records before closing ResultSet.

于 2012-04-15T18:58:41.887 回答