Count the number of rows in a Oracle database table

From CodeCodex


Using an SQL Query[edit]

// Get a record count with the SQL Statement
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) AS rowcount FROM 

// Get the rowcount column value.
int ResultCount = rs.getInt(rowcount) ;

rs.close() ;

Using JDBC Scrollable ResultSet[edit]

sqlString = "SELECT * FROM emp";

// Create a scrollable ResultSet.
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sqlString);

// Point to the last row in resultset.

// Get the row position which is also the number of rows in the ResultSet.
int rowcount = rs.getRow(); 

System.out.println("Total rows for the query: "+rowcount);

// Reposition at the beginning of the ResultSet to take up call.

Using Oracle JDBC Cached RowSet[edit]

// Create and initialize Cached RowSet object.
OracleCachedRowSet ocrs = new OracleCachedRowSet();     
// Create a string that has the SQL statement that gets all the records.
String sqlString = "SELECT empno FROM emp";

// Create a statement, resultset objects.
stmt = conn.createStatement();
rs = stmt.executeQuery(sqlString);

// Populate the Cached RowSet using the above Resultset.
// Point to the last row in Cached RowSet.

// Get the row position which is also the number of rows in the Cached
// RowSet.
int rowcount = ocrs.getRow();

System.out.println("Total rows for the query using Cached RowSet: "+
// Close the Cached Rowset object.

if (ocrs != null)