Monday, February 21, 2011

Java: How do I get the size of a java.sql.ResultSet?

Shouldn't this be a pretty straightforward operation? However, I there is no size() or length() method.

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

    KG : Inside the if(rs.last()) code block, wouldn't the correct method be rs.beforeFirst() instead of rs.first()? This way, you are not skipping the first record in your result set for processing in the while loop.
    JeeBee : KG - Indeed that looks right at a brief look at the code!
  • ResultSet.last() followed by ResultSet.getRow() will give you the row count, but it may not be a good idea as it can mean reading the entire table over the network and throwing away the data. Do a SELECT COUNT(*) FROM ... query instead.

    JeeBee : last() and getRow() aren't static methods in the ResultSet class.
    laz : For brevity's sake I always reference methods in this fashion when writing about them to others, regardless of whether they are static or not. Actually creating an instance of the object and calling the method is implied.
  • For a detailed description of how to connect to SQLServer database from Java, Statement, PreparedStatment, CallableStatement, ResultSet objects etc. check this link: HOW TO: SQL in JAVA.

0 comments:

Post a Comment