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 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:
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.I've been attempting to set the current row to the first index (dealing with primary keys). I would suggest
When the ResultSet is populated, it points to before the first row. When setting it to the first row (indicated by
rs.absolute(1)
) it will return true denoting it was successfully placed at row 1, or false if the row does not exist. We can extrapolate this towhich sets the current row to position i and will fail if the row doesn't exist. This is just an alternative method to
According to the most viable answer the suggestion is to use "isBeforeFirst()". That's not the best solution if you don't have a "forward only type".
There's a method called ".first()". It's less overkill to get the exact same result. You check whether there is something in your "resultset" and don't advance your cursor.
The documentation states: "(...) false if there are no rows in the result set".
However, there's a difference between "isBeforeFirst()" and "first()". First generates an exception if done on a resultset from type "forward only".
Compare the two throw sections: http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#isBeforeFirst() http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#first()
Okay, basically this means that you should use "isBeforeFirst" as long as you have a "forward only" type. Otherwise it's less overkill to use "first()".
This is a practical and easy read piece I believe.
It is better to re execute query because when we call
if(rs.next()){....}
first row of ResultSet will be executed and after it insidewhile(rs.next()){....}
we'll get result from next line. So I think re-execution of query insideif
is the better option.