tags:

views:

4221

answers:

6

Resultset has no method for hasNext. I want to check if the resultSet has any value

is this the correct way

if (!resultSet.next() ) {
    System.out.println("no data");
}
+8  A: 

That's correct, initially the ResultSet's cursor is pointing to before the first row, if the first call to next() returns false then there was no data in the ResultSet.

ninesided
But keep in mind, if there /are/ rows, after that test you will be pointing to the first row. So make sure you don't accidentally skip a row.
Matthew Flaschen
+8  A: 

You would usually do something like this:

while ( resultSet.next() ) { 
   // Read the next item
   resultSet.getString("columnName");
}

If you want to report an empty set, add a variable counting the items read. If you only need to read a single item, then your code is adequate.

kgiannakakis
+3  A: 

That would work if you want to see if there are any rows in the result set yes.

Note that next() always moves to the next row, so if you are planning on doing any reading from the result set you need to take that into account.

Usual usage with ResultSet (when simply reading) is:

while (resultSet.next())
{
   ... read from the row here ...
}

Which obviously won't work correctly if you invoked next() once already to check if the result set was empty, so watch out for that. Although there are methods for "backing up", they are not supported for all types of result sets.

Nuoji
+4  A: 

you could always do the next up front, and just do a post loop check

if (!resultSet.next() ) {
    System.out.println("no data");
} else {

    do {
     //statement(s)
    } while (resultSet.next());
}
Maslow
A: 

I get empty result sets from queries that come out just fine on SQLPlus using JDBC. What's wrong?

jeremyjanson
Welcome to SO! If you have a question, click on "Ask Question" above (and be sure to provide enough detail for people to help).
Jim Ferrans
A: 

The normal way is that you don't check this inside the data layer, but in the business layer. For existance of a row, just let DAO class return boolean which you can check further. For an unique row, just let DAO class return javabean Object which you can test if it is null or not. For multiple rows, just let DAO class return List or Set which you can call size() on to get amount of rows. None of this all is DAO class' responsiblity.

For code examples consult this answer.

BalusC