record-count jdbc row - How do I get the size of a java.sql.ResultSet?

7 Answers

ResultSet rs = ps.executeQuery();
int rowcount = 0;
if (rs.last()) {
  rowcount = rs.getRow();
  rs.beforeFirst(); // not rs.first() because the below will move on, missing the first element
while ( {
  // do your standard per row stuff
records code to

Shouldn't this be a pretty straightforward operation? However, I see there's neither a size() nor length() method.

int i = 0;
while( {

It is a simple way to do rows-count.

ResultSet rs = job.getSearchedResult(stmt);
int rsCount = 0;

//but notice that you'll only get correct ResultSet size after end of the while loop
    //do your other per row stuff 
    rsCount = rsCount + 1;
}//end while

[Speed consideration]

Lot of ppl here suggests ResultSet.last() but for that you would need to open connection as a ResultSet.TYPE_SCROLL_INSENSITIVE which for Derby embedded database is up to 10 times SLOWER than ResultSet.TYPE_FORWARD_ONLY.

According to my micro-tests for embedded Derby and H2 databases it is significantly faster to call SELECT COUNT(*) before your SELECT.

Here is in more detail my code and my benchmarks

        String sql = "select count(*) from message";
        ps =  cn.prepareStatement(sql);

        rs = ps.executeQuery();
        int rowCount = 0;
        while( {
            rowCount = Integer.parseInt(rs.getString("count(*)"));
        System.out.println("Count : " + rowCount);


theStatement=theConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

ResultSet theResult=theStatement.executeQuery(query); 

//Get the size of the data returned
int size = theResult.getRow() * theResult.getMetaData().getColumnCount();       

Give column a name..

String query = "SELECT COUNT(*) as count FROM

Reference that column from the ResultSet object into an int and do your logic from there..

PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, item.getProductId());
ResultSet resultSet = statement.executeQuery();
while ( {
    int count = resultSet.getInt("count");
    if (count >= 1) {
        System.out.println("Product ID already exists.");
    } else {
        System.out.println("New Product ID.");