Java 中的 ResultSet 可以为“null”吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18301326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:16:34  来源:igfitidea点击:

Can a ResultSet be 'null' in Java?

javasqljdbcnullresultset

提问by DeaIss

I have a very basic bit of code which executes a select query and returns a boolean depending if the result set is empty or not.

我有一个非常基本的代码,它执行一个选择查询并根据结果集是否为空返回一个布尔值。

public boolean checkIfUserHasPreferences(String username){
        ResultSet rs = null;
        boolean checkBoolean = false;

        try {
            DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
            con = DriverManager.getConnection(Messages.getString("OracleUserManagement.0"), Messages.getString("OracleUserManagement.1"), Messages.getString("OracleUserManagement.2")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

            PreparedStatement statement = con.prepareStatement("SELECT USERNAME FROM USER_PREFERENCES WHERE USERNAME = ?"); 
            statement.setString(1, username);
            rs = statement.executeQuery();
            if (rs == null){
                System.out.println("I checked it was true!");
                checkBoolean = true;
            } else {
                System.out.println("I checked it was false!");
                checkBoolean = false;
            }

            con.commit();

            con.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return checkBoolean;
    }

What confuses is me that even though the table/database is empty, it always prints out "I checked it was false!".

让我感到困惑的是,即使表/数据库是空的,它也总是打印出“我检查过它是假的!”。

Is this because even if a result set returns 0 rows, it does not = null? Should I be using while (rs.next()) to check instead?

这是因为即使结果集返回 0 行,它也不会 = null?我应该使用 while (rs.next()) 来检查吗?

采纳答案by Rohit Jain

You could have looked onto the API of Statement#executeQuery()method. It says:

您可以查看Statement#executeQuery()方法的 API 。它说:

Returns:

  • a ResultSet object that contains the data produced by the given query; never null

返回:

  • 一个 ResultSet 对象,包含给定查询生成的数据;从不为空

Emphasis mine.

强调我的。

Should I be using while (rs.next()) to check instead?

我应该使用 while (rs.next()) 来检查吗?

Yes.

是的。

回答by sactiw

No, ResultSet returned by executeQuery(java.lang.String) method can never be null.

不,executeQuery(java.lang.String) 方法返回的 ResultSet永远不能为 null

Moreover, the standard way to check whether a ResultSet is empty or not is to try setting its cursor to first row by using its first()and if it returns false it indicates that ResultSet is empty.

此外,检查 ResultSet 是否为空的标准方法是尝试使用它将其游标设置为第一行first(),如果返回 false 则表示 ResultSet 为空。

So, in your case you don't even need to check rather just return rs.first();

所以,在你的情况下,你甚至不需要检查,而只是 return rs.first();

For example:

例如:

if (!rs.first()) {
    // handle empty set: throw error or return
}

// continue processing the ResultSet further
do {
    // ...
} while (rs.next());

回答by padippist

The result set will not be null until and unless:

结果集不会为空,除非:

1.It is initialized to null and done nothing else,

2.If the statement on which execute query is written is not correct(sql exception will occur and initialization will not happen).

1.它被初始化为null并且什么都不做,

2.如果execute query写的语句不正确(会出现sql异常,不会初始化)。

This is irrelevant for this question, but will serve as a tip for people like me.

这与这个问题无关,但可以作为像我这样的人的提示。

This happen when database operation is done in a separate class where statement.executeQuery() is given in try-catch which has no e.printStackTrace() or any other logging mechanics.

当数据库操作在一个单独的类中完成时会发生这种情况,其中 statement.executeQuery() 在 try-catch 中给出,它没有 e.printStackTrace() 或任何其他日志记录机制。

I have confronted with this error and that is the reason why I am writing. This can be a great problem when we do a batch process where one out of 50000 execution causes an exception(in my case:

我遇到了这个错误,这就是我写作的原因。当我们执行批处理时,50000 次执行中有一个会导致异常(在我的情况下:

com.ibm.db2.jcc.a.SqlException: DB2 SQL error: SQLCODE: -805, SQLSTATE: 51002

com.ibm.db2.jcc.a.SqlException:DB2 SQL 错误:SQLCODE:-805,SQLSTATE:51002

this error was caused around 20000 iteration ) which causes unwanted result.

这个错误是由大约 20000 次迭代引起的),这会导致不需要的结果。