如何获取 ResultSet 包含的行数?

发布于 2024-12-10 10:46:06 字数 138 浏览 0 评论 0原文

我的查询旨在返回一行(因为它是通过唯一 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心凉 2024-12-17 10:46:06

我认为没有办法在单个方法调用中做到这一点。

您可以使用 ResultSet 的 last() 方法,然后调用 ResultSet 的 getRow() 方法,该方法将为您提供 ResultSet 大小,并在需要时根据需要抛出异常尺寸。

请记住使用finally子句来关闭所有连接/ds:)

rs.last();

if(rs.getRow() > 1) {
throw (...);
}

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 (...);
}
莳間冲淡了誓言ζ 2024-12-17 10:46:06
rs.first();
if(!rs.isLast())
     throw new Exception(...);

似乎您不需要知道返回的行数,只需知道返回的行数是否超过 1 即可。

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.

西瓜 2024-12-17 10:46:06

你有没有尝试过:
java.sql.ResultSet.isBeforeFirst()

来自 javadoc:
检索光标是否在此 ResultSet 对象中的第一行之前。

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文