13
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?

2
  • I just noticed that you said an exception was thrown when you called first(). Which exception is thrown? It may be throwing one because you're already used getRow(), or it may be throwing one because your driver doesn't support this method, in which case Colin's solution is more likely to work for you.
    – jasonmp85
    May 30, 2010 at 14:33
  • @jasonmp: You are right my driver does not support call to first(). I used Collin's solution and it is working for me.
    – Bruce
    May 31, 2010 at 4:23

10 Answers 10

21

The pattern I normally use is as follows:

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

if( empty ) {
    // Empty result set
}
2
  • 1
    this moves the cursor forward right ? so for further processing , the first record might be missed.
    – Tito
    Oct 22, 2012 at 4:32
  • You would miss the first record if you are processing records after this code. However, I usually process the records inside the same while loop. (Where the "//ResultSet processing here comment" is.) This works as expected and includes all rows. The downside it that you cannot just stick the check into a method. Oct 26, 2012 at 17:44
5

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)

3

You can do this too:

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

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

1

Why is execution not entering the while loop?

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.

2
1

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 ResultSet to a List of value objects each representing a table row entity and then just use the List methods to determine if there are any rows.

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:

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 answer for other JDBC examples.

1
  • What class is the list method from? It's not on resultset
    – Marcin
    Nov 1, 2017 at 16:59
1

CLOSE_CURSORS_AT_COMMIT

public static final int CLOSE_CURSORS_AT_COMMIT

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

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.

0

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
}
-1

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.