Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the count of rows in a Java resultset

Tags:

java

mysql

jdbc

Does anyone know a better way of getting the number of rows in a Java resultset returned from a MySQL database? The resultset returned is not going to be the total number of rows read from the database so I don't think I can use SQL's COUNT aggregate function.

public static int getResultSetRowCount(ResultSet resultSet) {     int size = 0;     try {         resultSet.last();         size = resultSet.getRow();         resultSet.beforeFirst();     }     catch(Exception ex) {         return 0;     }     return size; } 
like image 610
Mr Morgan Avatar asked Jun 16 '10 11:06

Mr Morgan


People also ask

How do I count the number of rows in Java?

The SQL Count() function returns the number of rows in a table. Using this you can get the number of rows in a table.

How do I find the number of rows in a ResultSet in SQL?

To number rows in a result set, you have to use an SQL window function called ROW_NUMBER() . This function assigns a sequential integer number to each result row. However, it can also be used to number records in different ways, such as by subsets.

Which command is used for counting the number of rows in the ResultSet?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.

How do you find the ResultSet length?

println("Total number of rows in ResultSet object = "+rowCount); Simply iterate on ResultSet object and increment rowCount to obtain size of ResultSet object in java. rowCount = rs. getRow();


1 Answers

A better answer is to forget about the number of rows until you've successfully loaded the ResultSet into an object or collection. You can keep the count of the number of rows with either of those options.

It's important to close ResultSets (and all SQL resources like Connection and Statement) in the narrowest method scope possible. That means not passing ResultSet out of the persistence layer. Better to get the number of rows using a Collection size() call.

Stop thinking about databases and start thinking in terms of objects. Java's an object-oriented language.

like image 146
duffymo Avatar answered Sep 23 '22 15:09

duffymo