How do I get the size of a java sql ResultSet

1.2K    Asked by MaryHoward in Java , Asked on Jul 27, 2021

I researched but found out there's neither a size() nor length() method. How to get java resultset size?

Answered by Rohit sharma

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

To get java resultset size reference that column from the ResultSet object into an int and do your logic from there..

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

Or you can probably 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
while(rs.next())
{
    //do your other per row stuff
    rsCount = rsCount + 1;
}//end while


Your Answer

Interviews

Parent Categories