2

I want to know how many rows in result set after executing the particular query

ResultSet rs = ps.executeQuery();

how get the size of rs??? thanx in advance

java baba
  • 2,199
  • 13
  • 33
  • 45

3 Answers3

12

If you just want the number of rows in the ResultSet, you can do :

int size= 0;
if (rs != null)   
{  
  rs.beforeFirst();  
  rs.last();  
  size = rs.getRow();  
}  
jester
  • 3,491
  • 19
  • 30
  • 2
    That is only guaranteed to work for scrollable resultsets, type forward only resultsets should throw an `SQLException` when `beforeFirst()` or `last()` are called (although some implementations don't do that). – Mark Rotteveel Nov 07 '13 at 09:08
  • This would mean reading the entire table over the network and throwing away the data after, it would be far better to simply execute a count(*) sql query instead – MRDJR97 May 17 '18 at 12:24
4

by doing while loop:

int size=0;
while (rs.next()) {
    size++;
}
Baby
  • 5,062
  • 3
  • 30
  • 52
0

You need not to iterate it and count the number of rows. You can try the following easy approach

boolean b = rs.last();
int numberOfRecords = 0;
if(b){
    numberOfRecords = rs.getRow();
}
Nick Humrich
  • 14,905
  • 8
  • 62
  • 85
shikjohari
  • 2,278
  • 11
  • 23