Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the row count in JDBC?

I've executed a JDBC query to obtain a resultset. Before iterating over it, I'd like to quickly find out how many rows were returned. How can I do this with high performance?

I'm using Java 6, Oracle 11g, and the latest Oracle JDBC drivers.

like image 380
Steve McLeod Avatar asked Oct 02 '08 14:10

Steve McLeod


People also ask

How do you count rows in Java?

How to count rows – count (*) and Java. The SQL Count() function returns the number of rows in a table. Using this you can get the number of rows in a table.

How do you get total row count?

Just click the column header. The status bar, in the lower-right corner of your Excel window, will tell you the row count. Do the same thing to count columns, but this time click the row selector at the left end of the row. If you select an entire row or column, Excel counts just the cells that contain data.

How do you count rows in a database?

To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.

How do I get the row count in a table in SQL?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).


1 Answers

You're going to have to do this as a separate query, for example:

SELECT COUNT(1) FROM table_name 

Some JDBC drivers might tell you but this is optional behaviour and, more to the point, the driver may not know yet. This can be due to how the query is optimised eg two example execution strategies in Oracle are to get all rows as quickly as possible or to get the first row as quickly as possible.

If you do two separate queries (one a count and the other the query) then you'll need to do them within the same transaction. This will work well on Oracle but can be problematic on other databases (eg SQL Server will either show you uncommitted data or block on an external uncommitted update depending on your isolation level whereas Oracle supports an isolation level that gives you a transactionally consistent view of the data without blocking on external updates).

Normally though it doesn't really matter how many rows there are. Typically this sort of query is either batch processed or paged and either way you have progress information in the form of rows loaded/processed and you can detect the end of the result set (obviously).

like image 179
cletus Avatar answered Sep 20 '22 02:09

cletus