为什么是"while(rs.next())"?这里有必要吗? [英] Why is "while (rs.next())" necessary here?

查看:109
本文介绍了为什么是"while(rs.next())"?这里有必要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从数据库"日志"中选择最大行数,并将其存储在变量m中.

I want to select the maximum line number from my database "Logs" and store it in a variable m.

这是我的代码:

ResultSet rs = stmt.executeQuery("Select max(Line) as L from logs");

while (rs.next()) {          // Why do I need this
    int m = rs.getInt("L");
    System.out.println(m);
}

但是除非我使用while(rs.next()),否则它不起作用.

But it doesn't work unless I use while(rs.next()).

如果我理解正确,则rs.next()将光标移动到下一行,但是在此结果中,我只有一行.

If I understand correctly, rs.next() moves the cursor to the next row, but here, in this result, I only have one row.

那么,有人可以解释为什么需要循环吗?我唯一想到的是第一个光标设置在列名上,对吗?

So, can someone explain why the loop is necessary? The only thing I can think of is that the first cursor is set on the column name, am I right?

推荐答案

为什么?

最初将光标放置在第一个元素的之前.您需要推进一次以访问第一个元素.

Why?

The cursor is initially placed before the first element. You need to advance it once to access the first element.

显然是这样做的,因为如您所见,使用循环遍历结果非常方便.从官方文档:

This was obviously done because traversing the results using a loop is very convenient then, as you see. From the official documentation:

将光标从其当前位置向前移动一行. ResultSet光标最初位于第一行之前;第一个对方法的调用接下来使第一行成为当前行;第二个调用使第二行成为当前行,依此类推.

Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.


解决方案

因此,虽然不需要任何循环,但需要将光标前进一次.从技术上说,一个rs.next();就足够了:


Solution

So, while you don't need any loop, you need to advance the cursor once. A single rs.next(); would technically be enough:

rs.next();
// Access the result

但是,您可能要考虑根本不存在匹配的情况,因为:

However, you probably want to account for the case where there was no match at all, since:

当对next方法的调用返回false时,光标将位于最后一行之后. 任何需要当前行的ResultSet方法的调用都会导致抛出SQLException.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.

因此,在这种情况下,代码将失败.

So the code would fail in this case.

因此,您应该对案件进行说明,并使用返回的boolean来保护您的访问权限:

Because of that, you should account for the case and use the returned boolean to guard your access:

if (rs.next()) {
    // Access result ...
} else {
    // No match ...
}

这篇关于为什么是"while(rs.next())"?这里有必要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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