How to get a number of rows a ResultSet contains?

早过忘川 提交于 2019-12-13 06:58:38

问题


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?


回答1:


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 (...);
}



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/7808350/how-to-get-a-number-of-rows-a-resultset-contains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!