如何查找ResultSet.next()方法的jdk源代码

今天在做一个数据库查询的时候遇到一个关于ResultSet.next()方法的问题。
在查询出结果集以后,如果我先调用一次ResultSet.next()以后,再次调用ResultSet.next()就会出现空指针异常。代码如下:
pstm3 = connection.prepareStatement(sql2);

        rsResult = pstm3.executeQuery();
        boolean flag=rsResult.next(); 
        System.err.println(flag+"------");
        if (rsResult.next()) {
            jysString = rsResult.getString(6);
        }

如果我直接循环结果集就没有问题:
pstm3 = connection.prepareStatement(sql2);

        rsResult = pstm3.executeQuery();
        if (rsResult.next()) {
            jysString = rsResult.getString(6);
        }

所以,我就想看ResultSet.next()方法是怎么实现的,在eclipse中我点进去这个方法,却发现这只是一个接口
boolean next() throws SQLException;

所以我想问一下,ResultSet.next()的机制是什么样的,怎么在eclipse中查看它的源代码?
谢谢各位

阅读 3.4k
2 个回答

A ResultSet is initially positioned before its first row, the first
call to next makes the first row the current row; the second call
makes the second row the current row, etc. If an input stream from the
previous row is open, it is implicitly closed. The ResultSet's warning
chain is cleared when a new row is read

上面是文档的描述,意思是当你调用一次next()的时候,游标即文中提到的position会往下移动。

另附next源码如下:

public boolean next() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {

            if (this.onInsertRow) {
                this.onInsertRow = false;
            }

            if (this.doingUpdates) {
                this.doingUpdates = false;
            }

            boolean b;

            if (!reallyResult()) {
                throw SQLError.createSQLException(Messages.getString("ResultSet.ResultSet_is_from_UPDATE._No_Data_115"), SQLError.SQL_STATE_GENERAL_ERROR,
                        getExceptionInterceptor());
            }

            if (this.thisRow != null) {
                this.thisRow.closeOpenStreams();
            }

            if (this.rowData.size() == 0) {
                b = false;
            } else {
                this.thisRow = this.rowData.next();

                if (this.thisRow == null) {
                    b = false;
                } else {
                    clearWarnings();

                    b = true;

                }
            }

            setRowPositionValidity();

            return b;
        }
    }
    
    
    

这里可以看出来,在游标移动之前会进行判断(判断是否在进行插入,修改,锁表的机制),随后会有检查next是否有值的判断。在你的代码中,先调用了next(),然后直接又调用了一次next(),出现这种情况的可能是你第一次next()为false,如果第一次为true,那么就跟你的while运行的结果一样,因为如果第一次next()为false,可能是触发了closeOpenStreams(),具体以debug为准。

新手上路,请多包涵

点进去是接口,说明jdk只定义了接口,源码需要第三方自己实现,类似servlet的api,根据不同的第三方服务提供商,实现也会有差异。如果你用的数据库是mysql,ResultSet的具体实现可以在mysql-connector-java.jar这种第三方jar里找

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题