Friday, August 13, 2010

How to get the size of ResultSet (total number of rows/columns)?

To Get ColumnCount:

ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();

To Get RowCount:

1. Using Query


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

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

rs.close() ;


2. Using Scrollable ResultSet:


String strQuery = "SELECT * FROM Person";

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

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

No comments:

Post a Comment