以下是javadoc中的注释:
boolean java.sql.ResultSet.next() throws SQLException
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 methodnext
makes the first row the current row; the second call makes the second row the current row, and so on.When a call to the
next
method returnsfalse
, the cursor is positioned after the last row. Any invocation of aResultSet
method which requires a current row will result in aSQLException
being thrown. If the result set type isTYPE_FORWARD_ONLY
, it is vendor specified whether their JDBC driver implementation will returnfalse
or throw anSQLException
on a subsequent call tonext
.If an input stream is open for the current row, a call to the method
next
will implicitly close it. AResultSet
object's warning chain is cleared when a new row is read.
渣翻一下:
将指针移动到当前位置的下一行。ResultSet 指针的初始位置位于第一行之前;第一次调用next()方法将会把第一行设置为当前行;第二次调用next()方法指针移动到第二行,以此类推。
当对next()方法调用返回 false,说明此时指针位于最后一行之后。所有对 ResultSet 需要使用当前行的方法[注:如getString()、getInt()等等]的调用都将导致next()方法抛出 SQLException 异常。如果返回的 ResultSet 集合的类型被设置为 TYPE_FORWARD_ONLY ,会在随后对next()方法的调用中返回 false 或抛出 SQLException 异常,因不同的数据库提供者的 JDBC 驱动实现而异。
如果为当前行打开了一个输入流,对next()方法的调用将会隐式地关闭它。
当新的一行读入时,ResultSet对象的警告链将被清空。
这里需要注意的是:
1. 开始指针位置位于第一行之前,也就是说,第一次调用next()方法后才能开始获取数据。这种做法的好处在于可以方便地配合while进行遍历,而不用担心取不到第一行。
while(re.next()){
//re.getXXX()
}
2. 指针移动到最后一行之后返回false,可以用作循环结束的条件。在两种情况下:遍历到最后一行之后;或者当 ResultSet 中没有元素、行数为0时,返回false退出循环。