Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ResultSet getFetchSize() doesn't seem to work?

Tags:

java

sql

jdbc

I'm having trouble with the getFetchSize() function.

I simply need to know if the SQL query has returned zero rows.

I've tried this simple statement:

if (rs.getFetchSize()==0)
    System.out.println("HEADLINE");

where rs is of the ResultSet type. The above code doesn't seem to work. It always prints the message whether rs is empty or not.

I checked the SQL query itself and it correctly returned non-empty result when rows existed.

Any thoughts on how I can determine whether the query has returned 0 rows? I googled it and couldn't find any answer.

like image 278
ronn jack Avatar asked Jan 11 '13 10:01

ronn jack


People also ask

How do you retrieve values in a ResultSet?

Invoke the Statement. executeQuery method to obtain the result table from the SELECT statement in a ResultSet object. In a loop, position the cursor using the next method, and retrieve data from each column of the current row of the ResultSet object using getXXX methods.

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

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.

What is getFetchSize?

int. getFetchSize() Retrieves the fetch size for this ResultSet object.

How can you tell if a record is last ResultSet?

The isAfterLast() method of the ResultSet interface is used to determine whether the cursor is on the last row of the ResultSet. rs. isLast(); This method returns an boolean this value is true, if the cursor is on the last row of the ResultSet else, it returns false.


2 Answers

ResultSet.getFetchSize() doesn't return the number of results! From here:

Standard JDBC also enables you to specify the number of rows fetched with each database round-trip for a query, and this number is referred to as the fetch size

You can iterate across the result set and if you don't have any entries, then you can determine that you got no results. Why can't you get the result size immediately ? Because the database is returning you a pointer to its results and it's relying on you to iterate through that (going back to the server for each row).

like image 129
Brian Agnew Avatar answered Sep 19 '22 21:09

Brian Agnew


The fetch size is the number of rows that should be retrieved from the database in each roundtrip. It has nothing to do with the number of rows returned.

What you should do is call rs.next() - iff your query didn't return any rows it will return false.

like image 41
Jens Borgland Avatar answered Sep 19 '22 21:09

Jens Borgland