【问题标题】:I am getting error "java.sql.SQLException: After end of result set" while trying to access this returned resultSetCustomer.from other methode我在尝试从其他方法访问此返回的 resultSetCustomer. 时收到错误“java.sql.SQLException:结果集结束后”
【发布时间】:2021-02-26 14:48:22
【问题描述】:
 public ResultSet getAllCustomer() throws SQLException{
  //List L = new ArrayList();
    try {
           stm = con.prepareStatement("select * from customer");
     
      resultSetSubject = stm.executeQuery();
        while (resultSetCustomer.next()) {
            
            //L.add(resultSetCustomer);
            
         resultSetCustomer.getInt(1);
             resultSetCustomer.getString(2);
             
           
            
            //System.out.println(resultSetCustomer.getInt("id")+" "+resultSetCustomer.getString("name"));
           
        }
    } catch (Exception e) {
         System.out.println(e);
    } 
     
       
  return resultSetCustomer;
   
}

简单来说,我正在从客户表中获取所有记录并作为结果集返回。我正在访问返回的结果集

结果集 rs = T.getAllCustomer();

          System.out.println(rs.getInt("id")+" "+rs.getString("name")); 

【问题讨论】:

    标签: java jdbc resultset


    【解决方案1】:

    您的代码中有几个问题:

    1. 您正在获取一个ResultSet 对象,遍历其中的所有行,获取列值,然后返回此ResultSet 对象。当它返回给调用者时,它已经被处理行的循环所消耗(这是您问题中错误的原因)。

    2. 不要返回ResultSet 对象,而是创建一个映射到数据库中数据的Customer 实体类,并返回Customer 的一个实例。返回一个ResultSet 对象真的很糟糕,因为它不能控制对象的关闭方式,也不能让你的代码面向对象。

    3. 如果您没有参数化查询,则无需创建准备好的语句。

    4. 完成后Statement(和ResultSet)必须是closed。您应该将处理整个结果的代码包装在 try-with-resources statement 中。

    【讨论】:

    • 感谢您的帮助。请注意,我的程序需要返回结果集而不是任何客户实例。我做了关闭语句和结果集,但是它显示错误,因此尝试其他过程来测试粘贴的avobe。解决方案需要是我如何返回结果集。请对此有任何意见,我该怎么做?
    • @NEHASURDESHAI 代码中的主要问题是您正在处理方法本身中的结果集(while (resultSetCustomer.next()) { 循环)。这部分应该由方法的调用者完成,而不是方法本身。在方法中处理结果集是在消耗结果集,因此调用者尝试使用它时会导致错误。
    【解决方案2】:

    您的代码几乎不需要修改

    1 > 确保您使用的结果集变量与定义的相同(在您的代码中有所不同)。

    2> 仅使用

    public ResultSet getAllCustomer() throws SQLException{
    try {
           stm = con.prepareStatement("select * from customer");
     
      resultSetCustomer = stm.executeQuery();
       
    } catch (Exception e) {
         System.out.println(e);
    }  
      return resultSetCustomer;
    

    }

    3> 以单独的方法关闭连接/结果集/语句,否则会出错。你可以使用如下

    public void close() throws SQLException{
         
         if (resultSetCustomer != null) {
             resultSetCustomer .close();
         }
         if (stm !=null) {
             stm.close();
         }
     }
    

    4> 访问时使用结果集(你的结果集实例).next()

    【讨论】:

    • 感谢它的工作.. 只是我需要在调用时在 2 个地方使用 next()
    猜你喜欢
    • 2020-09-09
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多