Count the number of rows in a Oracle database table

From CodeCodex

Java[edit]

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 
                                 emp");
rs.next();

// 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.
rs.last(); 

// 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 rs.next() call.
rs.beforeFirst();

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.
ocrs.populate(rs);
      
// Point to the last row in Cached RowSet.
ocrs.last();      

// 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: "+
                   rowcount);          
    
// Close the Cached Rowset object.

if (ocrs != null) 
  ocrs.close();