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

查看:246
本文介绍了java - 如何查找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中查看它的源代码?
谢谢各位

解决方案

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为准。

这篇关于java - 如何查找ResultSet.next()方法的jdk源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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