Search code examples
javajdbcresultset

I am getting error "java.sql.SQLException: After end of result set" while trying to access this returned resultSetCustomer.from other methode


 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;
   
}

Let me brief, I am fetching all record from the customer table and returning as resultset. I am accessing returned resultset as

ResultSet rs = T.getAllCustomer();

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

Solution

  • Your code needed little amendment

    1 > Ensure resultset variable you use are same as defined (one place its different in your code).

    2> use only

    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> Close your connection/resultset/statement in separate method otherwise you will get error. you can use as below

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

    4> use resultset(your resultset instance).next() while accessing