如何获取ResultSet包含的行数? [英] How to get a number of rows a ResultSet contains?

查看:292
本文介绍了如何获取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?

推荐答案

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

I don't think there is a way to do this in a single method call.

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

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.

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

Pls remember to have the finally clause to close all the connection/ds :)

rs.last();

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

这篇关于如何获取ResultSet包含的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆