Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 894
Bruce Avatar asked May 30 '10 13:05

Bruce


2 Answers

The pattern I normally use is as follows:

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

if( empty ) {
    // Empty result set
}
like image 126
Colin Gislason Avatar answered Sep 21 '22 12:09

Colin Gislason


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;");

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

References

ResultSet (Java Platform SE 6)

like image 24
jasonmp85 Avatar answered Sep 22 '22 12:09

jasonmp85