-1
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/onlineshop?autoReconnect=true&useSSL=false","root",DatabaseConnection.root);
PreparedStatement ps=con.prepareStatement("select * from custinfo");
ResultSet rs=ps.executeQuery();
/*******
//for counting the number of rows in result set
if(rs.last()) {
  x=rs.getRow();
  rs.beforeFirst();
}

When I'm trying to execute it it showing me the error:

java.sql.SQLException: Operation not allowed for a result set of type ResultSet.TYPE_FORWARD_ONLY.

Can you help me how can I solve this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    Well the exception exactly tells you what the problem is. rs.last() moves the cursor to the last row and return true is it is a valid row (non empty resultset). Then you ask it to move before the first row, but the cursor does not allow you to do so because "A default ResultSet object is not updatable and has a cursor that moves forward only" (as described in the ResultSet class javadoc ;-) ). – KDW Jan 27 '23 at 20:44
  • To be complete: why scrolling over an entire result set to count the number of rows... Use the appropriate SELECT statement for that purpose. Scrolling over every row just for the sake of counting is VERY inefficient. – KDW Jan 27 '23 at 20:49
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jan 28 '23 at 09:36

1 Answers1

0

The error message says it all - the ResultSet is of TYPE_FORWARD_ONLY, so you can't scroll it back with beforeFirst(). Having said that, querying the entire table (and having to send all that data from the database to your application) just to get its size is probably not a good practice. It would be much easier to use an aggregate query to get the number of rows:

try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/onlineshop?autoReconnect=true&useSSL=false","root",DatabaseConnection.root);
     PreparedStatement ps = con.prepareStatement("select count(*) from custinfo");
     ResultSet rs = ps.executeQuery()) {
    
     if (rs.next()) {
         size = rs.getInt(1);
     }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350