How to get the size of resultset in Java without iterating though ResultSet object?

Often many of us would come across such a situation where we need to know the size of the resultset returned from a database query without iterating the ResultSet object.

I also encountered a similar situation where, I needed to create an object with all the information of a particular row.

Consider this example.I have a person_info table, where I have the information like person_id,first_name,last_name,middle_name,mobile,city,gender,date_of_birth,age etc.

Now I need to query the database and for every row returned I need to create an JSONObject array like,

JSONObject json[]=new JSONObject[SIZE];

So, we have to initialize the size before iterating through ResultSet object.

After doing a lot of mistakes, found the right way to do this. Here it is.

 Statement st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
 ResultSet rs=st.executeQuery("SELECT * from persons");

 int SIZE= 0;
 if (rs != null)
 size = rs.getRow();

System.out.println("SIZE: "+size);

Happy Coding 🙂



  1. @myjavaprogramming
    Thanks for the link 🙂 It makes the java code more readable. But tad didn’t work for me.
    I found this elsewhere which worked for me.
    sourcecode language=’java’

    Please add this to your post.It might help someone. 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s