Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Number of Rows returned by ResultSet in Java

Tags:

java

resultset

I have used a ResultSet that returns certain number of rows. My code is something like this:

ResultSet res = getData(); if(!res.next()) {     System.out.println("No Data Found"); } while(res.next()) {     // code to display the data in the table. } 

Is there any method to check the number of rows returned by the ResultSet? Or do I have to write my own?

like image 337
Kiran Avatar asked Nov 28 '11 06:11

Kiran


People also ask

How do I count ResultSet rows in Java?

Getting the number of rows using methodsThe last() method of the ResultSet interface moves the cursor to the last row of the ResultSet and, the getRow() method returns the index/position of the current row.

How do you find the count of a ResultSet?

You can get the column count in a table using the getColumnCount() method of the ResultSetMetaData interface. On invoking, this method returns an integer representing the number of columns in the table in the current ResultSet object.

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.


2 Answers

First, you should create Statement which can be move cursor by command:

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); 

Then retrieve the ResultSet as below:

ResultSet rs = stmt.executeQuery(...); 

Move cursor to the latest row and get it:

if (rs.last()) {     int rows = rs.getRow();     // Move to beginning     rs.beforeFirst();     ... } 

Then rows variable will contains number of rows returned by sql

like image 100
Tu Tran Avatar answered Sep 21 '22 22:09

Tu Tran


You could use a do ... while loop instead of a while loop, so that rs.next() is called after the loop is executed, like this:

if (!rs.next()) {                            //if rs.next() returns false                                              //then there are no rows.     System.out.println("No records found");  } else {     do {         // Get data from the current row and use it     } while (rs.next()); } 

Or count the rows yourself as you're getting them:

int count = 0;  while (rs.next()) {     ++count;     // Get data from the current row and use it }  if (count == 0) {     System.out.println("No records found"); } 
like image 42
Jesper Avatar answered Sep 20 '22 22:09

Jesper