如何确定获取的 Java ResultSet 是否为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2938812/
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-13 14:40:12  来源:igfitidea点击:

How to find out if a Java ResultSet obtained is empty?

javadatabasejdbcresultset

提问by Bruce

Class.forName("org.sqlite.JDBC");
Connection conn =
    DriverManager.getConnection("jdbc:sqlite:userdata.db");
Statement stat = conn.createStatement();

ResultSet rs = stat.executeQuery("SELECT * from table WHERE is_query_processed = 0;");

int rowcount = rs.getRow(); 
System.out.println("Row count = "+rowcount); // output 1

rs.first(); // This statement generates an exception

Why is it so?

为什么会这样?

采纳答案by Colin Gislason

The pattern I normally use is as follows:

我通常使用的模式如下:

boolean empty = true;
while( rs.next() ) {
    // ResultSet processing here
    empty = false;
}

if( empty ) {
    // Empty result set
}

回答by karim79

You can do this too:

你也可以这样做:

rs.last();
int numberOfRows = rs.getRow();
if(numberOfRows) {
    rs.beforeFirst();
    while(rs.next()) {
        ...
    }
}

回答by Inv3r53

 while (results.next())

is used to iterate over a result set.so results.next() will return false if its empty.

用于迭代结果集。因此,如果结果为空,则 results.next() 将返回 false。

回答by jasonmp85

Here's a simple method to do it:

这是一个简单的方法:

public static boolean isResultSetEmpty(ResultSet resultSet) {
    return !resultSet.first();
}

Caveats

注意事项

This moves the cursor to the beginning. But if you just want to test whether it's empty, you probably haven't done anything with it yet anyways.

这会将光标移动到开头。但是如果你只是想测试它是否为空,你可能还没有对它做任何事情。

Alternatively

或者

Use the first()method immediately, before doing any processing. ResultSet rs = stat.executeQuery("SELECT * from table WHERE is_query_processed = 0;");

first()在进行任何处理之前立即使用该方法。ResultSet rs = stat.executeQuery("SELECT * from table WHERE is_query_processed = 0;");

if(rs.first()) {
    // there's stuff to do
} else {
    // rs was empty
}

References

参考

ResultSet (Java Platform SE 6)

结果集(Java 平台 SE 6)

回答by stacker

Why is execution not entering the while loop?

为什么执行不进入while循环?

If your ResultSet is empty the rs.next()method returns false and the body of the while loop isn't entered regardless to the rownumber (not count) rs.getRow()returns. Colins example works.

如果您的 ResultSet 为空,则该rs.next()方法返回 false 并且无论行号(不计数)rs.getRow()返回如何,都不会输入 while 循环的主体。柯林斯的例子有效。

回答by BalusC

Shifting the cursor forth and back to determine the amount of rows is not the normal JDBC practice. The normal JDBC practice is to map the ResultSetto a Listof value objects each representing a table row entity and then just use the Listmethods to determine if there are any rows.

来回移动光标以确定行数不是正常的 JDBC 实践。通常的 JDBC 实践是将 映射ResultSetList每个代表一个表行实体的值对象,然后只使用这些List方法来确定是否有任何行。

For example:

例如:

List<User> users = userDAO.list();

if (users.isEmpty()) {
    // It is empty!
if (users.size() == 1) {
    // It has only one row!
} else {
    // It has more than one row!
}

where the list()method look like as follows:

list()方法如下所示:

public List<User> list() throws SQLException {
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;
    List<User> users = new ArrayList<User>();

    try {
        connection = database.getConnection();
        statement = connection.createStatement();
        resultSet = statement.executeQuery(SQL_LIST);
        while (resultSet.next()) {
            User user = new User();
            user.setId(resultSet.getLong("id"));
            user.setName(resultSet.getString("name"));
            // ...
            users.add(user);
        }
    } finally {
        if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
        if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
        if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
    }

    return users;
}

Also see this answerfor other JDBC examples.

另请参阅此答案以了解其他 JDBC 示例。

回答by santosh kumar t

CLOSE_CURSORS_AT_COMMIT

CLOSE_CURSORS_AT_COMMIT

public static final int CLOSE_CURSORS_AT_COMMIT

公共静态最终 int CLOSE_CURSORS_AT_COMMIT

The constant indicating that ResultSet objects should be closed when the method Connection.commit is called. 

回答by joseluisbz

Try with this:

试试这个:

ResultSet MyResult = null;
MyResult = Conexion.createStatement().executeQuery("Your Query  Here!!!");
MyResult.last();
int NumResut = MyResult.getRow();MyResult.beforeFirst();
//Follow with your other operations....

This manner you'll be able work normally.

这样你就可以正常工作了。

回答by Chamod

May be you can convert your resultset object into String object and check whether is it empty or not.

也许您可以将结果集对象转换为 String 对象并检查它是否为空。

`if(resultset.toString().isEmpty()){
     // containg null result
 }
 else{
     //This conains the result you want
 }`

回答by Ullauri

This checks if it's empty or not while not skipping the first record

这会在不跳过第一条记录的情况下检查它是否为空

if (rs.first()) {
    do {
        // ResultSet is not empty, Iterate over it
    } while (rs.next());
} else {
    // ResultSet is empty
}