如何获取 ResultSet 包含的行数?
我的查询旨在返回一行(因为它是通过唯一 id 选择记录)。如果结果集为空,我将抛出一个异常;如果结果集包含多于 1 行,我将抛出另一个异常。恕我直言,在这种情况下,使用 while(rs.next()) 迭代结果集看起来不太漂亮。我可以立即获取结果集中的行数吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为没有办法在单个方法调用中做到这一点。
您可以使用 ResultSet 的
last()
方法,然后调用 ResultSet 的getRow()
方法,该方法将为您提供 ResultSet 大小,并在需要时根据需要抛出异常尺寸。请记住使用finally子句来关闭所有连接/ds:)
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 thegetRow()
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 :)
似乎您不需要知道返回的行数,只需知道返回的行数是否超过 1 即可。
Seems that you don't need to know the number of rows returned, just if there was more than 1.
你有没有尝试过:
java.sql.ResultSet.isBeforeFirst()
来自 javadoc:
检索光标是否在此 ResultSet 对象中的第一行之前。
Have you tried:
java.sql.ResultSet.isBeforeFirst()
From javadoc:
Retrieves whether the cursor is before the first row in this ResultSet object.