Month: January 2014

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)
 {
 rs.last();
 size = rs.getRow();
 rs.beforeFirst();
 }

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

Happy Coding 🙂