Reputation: 64207
A query of mine is meant to return exactly one row (as it is a select of a record by an unique id). I am to throw an exception if the result set is empty and another exception if it contains more than 1 row. Iterating throu the result set with while(rs.next()) doesn't look pretty in this case, IMHO. Can I just get the quantity of rows in a result set instantly?
Upvotes: 0
Views: 828
Reputation: 9307
Have you tried: java.sql.ResultSet.isBeforeFirst()
From javadoc: Retrieves whether the cursor is before the first row in this ResultSet object.
Note:Support for the isBeforeFirst method is optional for ResultSets with a result set type of TYPE_FORWARD_ONLY
Returns:
true if the cursor is before the first row; false if the cursor is at any other position or the result set contains no ro
Upvotes: 0
Reputation: 2109
I don't think there is a way to do this in a single method call.
You could use the last()
method of the ResultSet and then call the getRow()
method of the ResultSet which will give you ResultSet size and throw the exception if needed based on the size.
Pls remember to have the finally clause to close all the connection/ds :)
rs.last();
if(rs.getRow() > 1) {
throw (...);
}
Upvotes: 3
Reputation: 32949
rs.first();
if(!rs.isLast())
throw new Exception(...);
Seems that you don't need to know the number of rows returned, just if there was more than 1.
Upvotes: 3