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?
The pattern I normally use is as follows:
Here's a simple method to do it:
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;");References
ResultSet (Java Platform SE 6)
This checks if it's empty or not while not skipping the first record
Try with this:
This manner you'll be able work normally.
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.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 aList
of value objects each representing a table row entity and then just use theList
methods to determine if there are any rows.For example:
where the
list()
method look like as follows:Also see this answer for other JDBC examples.