如何检查结果集是否有一行或多行? [英] How to check if resultset has one row or more?

查看:26
本文介绍了如何检查结果集是否有一行或多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用JDBC检查结果集是否有一行或多行?

How to check if resultset has one row or more with JDBC?

推荐答案

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
boolean isMoreThanOneRow = rs.first() && rs.next();

你没有问这个,但你可能需要它:

You didn't ask this one, but you may need it:

boolean isEmpty = ! rs.first();

通常,我们不需要行数,因为我们使用 WHILE 循环而不是 FOR 循环来迭代结果集:

Normally, we don't need the row count because we use a WHILE loop to iterate through the result set instead of a FOR loop:

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
    // retrieve and print the values for the current row
    int i = rs.getInt("a");
    String s = rs.getString("b");
    float f = rs.getFloat("c");
    System.out.println("ROW = " + i + " " + s + " " + f);
}

但是,在某些情况下,您可能希望对结果进行窗口化,并且您需要提前记录计数以向用户显示类似 Row 1 to 10 of 100 的内容.您可以先使用 SELECT COUNT(*) 进行单独的查询,以获取记录计数,但请注意,该计数只是近似值,因为可以在执行所需的时间内添加或删除行两个查询.

However, in some cases, you might want to window the results, and you need the record count ahead of time to display to the user something like Row 1 to 10 of 100. You can do a separate query with SELECT COUNT(*) first, to get the record count, but note that the count is only approximate, since rows can be added or removed between the time it takes to execute the two queries.

来自结果集概述的示例

这篇关于如何检查结果集是否有一行或多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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