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");
}
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");
}
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
.
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.
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.
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());
}
I get empty result sets from queries that come out just fine on SQLPlus using JDBC. What's wrong?
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.