tags:

views:

449

answers:

3

How can I find out how many rows a MySQL query returns in Java?

+6  A: 

From the jdbc faq:

.18. There is a method getColumnCount in the JDBC API. Is there a similar method to find the number of rows in a result set?

No, but it is easy to find the number of rows. If you are using a scrollable result set, rs, you can call the methods rs.last and then rs.getRow to find out how many rows rs has. If the result is not scrollable, you can either count the rows by iterating through the result set or get the number of rows by submitting a query with a COUNT column in the SELECT clause.

Loki
A: 

I don't think you can, except maybe by calling ResultSet.last() and then ResultSet.getRow() - but I don't know if that will actually work. I've always just processed each row at a time, and counted them afterwards.

Paul Tomblin
A: 

If you use a CachedRowSet you can know how many rows your statement returned and iterate then both ways, forward and backwards, with the drawback that the full rowset must be placed in memory instead of being fetched dynamically. here more info.

Paulo Lopes