简体   繁体   中英

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")); 

There are several issues in your code:

  1. You are obtaining a ResultSet object, looping over all of the rows in it, getting the column values, and then returning this ResultSet object. By the time it is returned to the caller, it has already been consumed by the loop that processed the rows (this is the cause of the error in your question).

  2. Don't return the ResultSet object, instead create a Customer entity class that maps to the data in the DB, and return an instance of Customer . Returning a ResultSet object is really bad as it doesn't give control over how the object is closed, nor does it make your code object-oriented.

  3. You don't need to create a prepared statement if you don't have a parameterized query.

  4. The Statement (and ResultSet ) must be close d after done. You should wrap the code that processes the whole result in a try-with-resources statement .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM