| By Joseph Ottinger | Article Rating: |
|
| January 1, 2000 12:00 AM EST | Reads: |
10,776 |
If you already have your ResultSet, you have two choices, both bad: one is to keep a counter as you read the records in the ResultSet, and the other is to hope you have a compliant JDBC driver that supports the getRowCount() method. Both ways probably do the same thing: read the entire dataset. If you're interested in only a count of records, that's a lot of bandwidth down the drain (and memory, too, if you happen to need the data as you fly past it.)
A better approach is to run a separate query to determine the count of rows:
PreparedStatement ps=connection.prepareStatement("select count(*) from tablename");
ResultSet rs=ps.executeQuery();
rs.next();
int count=rs.getInt(1);
Note that if your query is complex enough, for some databases this will actually be slower than counting records as you iterate over the ResultSet.
If you've managed to set up a scrollable ResultSet, the following code might also work. Your author hasn't used it, as row counts haven't proven useful to him for some reason.
public static int getRowCount(ResultSet rs) throws SQLException {
int current = rs.getRow();
rs.last();
int count = rs.getRow();
if(count == -1)
count = 0;
if(current == 0)
rs.beforeFirst();
else
rs.absolute(current);
return count;
}
Reproduced with permission of http://java.enigmastation.com/index" The Undernet #Java Knowledge Base
Published January 1, 2000 Reads 10,776
Copyright © 2000 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Joseph Ottinger
Joseph Ottinger, formerly editor-in-chief of JDJ (2003-4), is a consultant with Fusion Alliance in Indianapolis and is one of the contributors to the OpenSymphony project.
- JDJ Archives: Eclipse vs NetBeans - "Point/Counterpoint" Special
- Java Trends - Exclusive Interview with Amy Fowler
- Java Viewpoint: "I'm Starting to Like Java Studio Creator..."
- Project Rave - First Thoughts
- Where Are the Components?
- How Can I Escape Quotes in SQL Queries?
- Let's Do Better
- Do Java and .NET Really Compete?
- For the Coming Year...
- The Culture Conflict
- It Just Works
- Sun Is Losing Its Way

























