Shouldn't this be a pretty straightforward operation? However, I see there's neither a size()
nor length()
method.
-
12I would love to know the reason for that omission.– SlamiceMar 4, 2012 at 6:53
-
My understanding of the question was that you want to find the size of the ResultSet IN BYTES, not the number of tuples...– DejanLekicDec 6, 2012 at 17:40
-
It's very annoying to have not the right dimension before process data, but if you have to store them in an array, you can consider using a data structure like List and then convert them to an array with the toArray() method.– AndreaTaroni86Sep 4, 2019 at 9:42
15 Answers
Do a SELECT COUNT(*) FROM ...
query instead.
OR
int size =0;
if (rs != null)
{
rs.last(); // moves cursor to the last row
size = rs.getRow(); // get row id
}
In either of the case, you won't have to loop over the entire data.
-
9
-
71For 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.– lazOct 10, 2008 at 18:23
-
51I write SomeClass.staticMethod() and SomeClass#instanceMethod() for less confusion.– JakeMay 13, 2011 at 3:17
-
9How does one fetch the value returned when executing a
select count
? Jun 2, 2011 at 9:14 -
21
ResultSet#last()
doesn't work on all types ofResultSet
objects, you need to make sure you use one that is eitherResultSet.TYPE_SCROLL_INSENSITIVE
orResultSet.TYPE_SCROLL_SENSITIVE
Jun 13, 2012 at 13:47
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
}
-
5Inside 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.– karlgrzJan 26, 2009 at 17:04
-
don't you forget to set the cursor back to beforeFirst outside the if block?– GobliinsJan 13, 2015 at 11:43
-
As ResultSet docs say,
getRow()
works forTYPE_FORWARD_ONLY
ResultSets, andbeforeFirst()
throws errors for those. Isn't this answer faulty then? Jul 20, 2016 at 0:08 -
6This only works when the statement is created with the scroll insensitive option:
ps=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
Feb 21, 2017 at 13:55
Well, if you have a ResultSet
of type ResultSet.TYPE_FORWARD_ONLY
you want to keep it that way (and not to switch to a ResultSet.TYPE_SCROLL_INSENSITIVE
or ResultSet.TYPE_SCROLL_INSENSITIVE
in order to be able to use .last()
).
I suggest a very nice and efficient hack, where you add a first bogus/phony row at the top containing the number of rows.
Example
Let's say your query is the following
select MYBOOL,MYINT,MYCHAR,MYSMALLINT,MYVARCHAR
from MYTABLE
where ...blahblah...
and your output looks like
true 65537 "Hey" -32768 "The quick brown fox"
false 123456 "Sup" 300 "The lazy dog"
false -123123 "Yo" 0 "Go ahead and jump"
false 3 "EVH" 456 "Might as well jump"
...
[1000 total rows]
Simply refactor your code to something like this:
Statement s=myConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
String from_where="FROM myTable WHERE ...blahblah... ";
//h4x
ResultSet rs=s.executeQuery("select count(*)as RECORDCOUNT,"
+ "cast(null as boolean)as MYBOOL,"
+ "cast(null as int)as MYINT,"
+ "cast(null as char(1))as MYCHAR,"
+ "cast(null as smallint)as MYSMALLINT,"
+ "cast(null as varchar(1))as MYVARCHAR "
+from_where
+"UNION ALL "//the "ALL" part prevents internal re-sorting to prevent duplicates (and we do not want that)
+"select cast(null as int)as RECORDCOUNT,"
+ "MYBOOL,MYINT,MYCHAR,MYSMALLINT,MYVARCHAR "
+from_where);
Your query output will now be something like
1000 null null null null null
null true 65537 "Hey" -32768 "The quick brown fox"
null false 123456 "Sup" 300 "The lazy dog"
null false -123123 "Yo" 0 "Go ahead and jump"
null false 3 "EVH" 456 "Might as well jump"
...
[1001 total rows]
So you just have to
if(rs.next())
System.out.println("Recordcount: "+rs.getInt("RECORDCOUNT"));//hack: first record contains the record count
while(rs.next())
//do your stuff
-
Interesting, but how would you dynamically/generically generate first select statements: cast(null as boolean)as MYBOOL, ect? For that you will need metadata of the "select" statement's fields and datatypes, like boolean, char, int, ect...) that might require extra DB trip that will negate all the benefits. Mar 31, 2016 at 14:25
-
This is useful when you do have access to all field details and speed is your main concern (and therefore need to stick with a fast
ResultSet.TYPE_FORWARD_ONLY
) May 21, 2017 at 21:56
int i = 0;
while(rs.next()) {
i++;
}
-
I don't understand what is the drawback of using this method to calculate ResultSet size. This is great...no use of an extra SQL parameter. Please comment on this method. Mar 13, 2015 at 5:21
-
6Performance is the keyword here. Imagine your resultset is 100M records then you will see the issue– PierreMay 13, 2016 at 16:49
-
9I want to know the result set size BEFORE processing the results because I need to make an array of the same size beforehand. And, as noted in other answers, scanning all rows twice won't always work.– IvoJan 10, 2017 at 22:10
-
@Ivo could you not use a List instead of an array because of noticeable performance degradation? Sep 16, 2020 at 20:27
-
1@jones-chris Who knows, this is 3 years ago, I have no clue what I was doing. I hate arrays though, so I assume using a List wasn't possible. Either way, an array should be more performant than a List (unless List methods get optimized by the runtime).– IvoSep 17, 2020 at 21:42
I got an exception when using rs.last()
if(rs.last()){
rowCount = rs.getRow();
rs.beforeFirst();
}
:
java.sql.SQLException: Invalid operation for forward only resultset
it's due to by default it is ResultSet.TYPE_FORWARD_ONLY
, which means you can only use rs.next()
the solution is:
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
-
13Switching from
ResultSet.TYPE_FORWARD_ONLY
toResultSet.TYPE_SCROLL_INSENSITIVE
usually incurs in a huge performance penalty. May 24, 2013 at 7:58 -
3I did test it on my table (10 columns, 187 392 rows). My test did query and load all elements to string. For TYPE_FORWARD_ONLY it took approx 1 second. For TYPE_SCROLL_INSENSITIVE it took approx 7 second. When I used rather
SELECT COUNT(*) FROM default_tbl
before theSELECT COUNT(*) FROM default_tbl
it took altogether less than 1.5 second. I tested on embedded derby database 10.11.1.1 May 19, 2015 at 12:07
[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.
The way of getting size of ResultSet, No need of using ArrayList etc
int size =0;
if (rs != null)
{
rs.beforeFirst();
rs.last();
size = rs.getRow();
}
Now You will get size, And if you want print the ResultSet, before printing use following line of code too,
rs.beforeFirst();
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
while(rs.next())
{
//do your other per row stuff
rsCount = rsCount + 1;
}//end while
-
5Yeah, that works. But I think the OP struggles with knowing the number of rows before actually processing them. Real life reasons I'd have to fight this issue so far: 1.) paging of record rows 2.) showing the rows processed in long-running tasks for progress monitoring purposes...– ppeterkaMay 24, 2013 at 7:23
-
Preallocating data structure size are another reason. I've seen plenty of libs return 10 element Lists when there is only a single value because the dev's had this same issue with ResultSet. Nov 21, 2013 at 17:24
String sql = "select count(*) from message";
ps = cn.prepareStatement(sql);
rs = ps.executeQuery();
int rowCount = 0;
while(rs.next()) {
rowCount = Integer.parseInt(rs.getString("count(*)"));
System.out.println(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
theResult.last();
int size = theResult.getRow() * theResult.getMetaData().getColumnCount();
theResult.beforeFirst();
I checked the runtime value of the ResultSet interface and found out it was pretty much a ResultSetImpl all the time. ResultSetImpl has a method called getUpdateCount()
which returns the value you are looking for.
This code sample should suffice:
ResultSet resultSet = executeQuery(sqlQuery);
double rowCount = ((ResultSetImpl)resultSet).getUpdateCount()
I realize that downcasting is generally an unsafe procedure but this method hasn't yet failed me.
-
3Not working with Tomcat/MySQL:
java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp.DelegatingResultSet cannot be cast to com.mysql.jdbc.ResultSetImpl
Jun 18, 2014 at 10:31 -
from the name
getupdatecount
, presumably this would only return a number of rows that gets updated, which wouldn't work if the statement is just reading data– jbuDec 17, 2021 at 10:08
Today, I used this logic why I don't know getting the count of RS.
int chkSize = 0;
if (rs.next()) {
do { ..... blah blah
enter code here for each rs.
chkSize++;
} while (rs.next());
} else {
enter code here for rs size = 0
}
// good luck to u.
I was having the same problem. Using ResultSet.first()
in this way just after the execution solved it:
if(rs.first()){
// Do your job
} else {
// No rows take some actions
}
Documentation (link):
boolean first() throws SQLException
Moves the cursor to the first row in this
ResultSet
object.Returns:
true
if the cursor is on a valid row;false
if there are no rows in the result setThrows:
SQLException
- if a database access error occurs; this method is called on a closed result set or the result set type isTYPE_FORWARD_ONLY
SQLFeatureNotSupportedException
- if the JDBC driver does not support this methodSince:
1.2
Easiest approach, Run Count(*) query, do resultSet.next() to point to the first row and then just do resultSet.getString(1) to get the count. Code :
ResultSet rs = statement.executeQuery("Select Count(*) from your_db");
if(rs.next()) {
int count = rs.getString(1).toInt()
}
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 (resultSet.next()) {
int count = resultSet.getInt("count");
if (count >= 1) {
System.out.println("Product ID already exists.");
} else {
System.out.println("New Product ID.");
}
}