Two Laptop Bag
The moose likes JDBC and Relational Databases and the fly likes Accessing data in ResultSet object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Accessing data in ResultSet object" Watch "Accessing data in ResultSet object" New topic

Accessing data in ResultSet object

lavanya shastri

Joined: Sep 22, 2009
Posts: 2
Hi ,

I need a little help with using the ResultSet object.
Basically, I have an sql query that is something like below

select count ( * ) from "UserBook" where "orderStatusID"= (select id from "OrderStatus" where name='NEW')

I execute this query and read it into a ResultSet object.Now the my problem is since the data baing returned is an Integer and not a bunch of rows/columns how do I access it from the ResultSet object

String query = select count ( * ) from "UserBook" where "orderStatusID"= (select id from "OrderStatus" where name='NEW') ;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);

How do I access the integer returned to the ResultSet object.

M K Rayapudi
Ranch Hand

Joined: Feb 19, 2007
Posts: 160
have you tried?

Anshul Agrawal

Joined: Jul 15, 2008
Posts: 19
write this query as
select count ( * ) AS COUNT from "UserBook" where "orderStatusID"= (select id from "OrderStatus" where name='NEW')

and fetch the record like
int count = rs.getInt("COUNT");
int count = rs.getInt(1);

lavanya shastri

Joined: Sep 22, 2009
Posts: 2
Rayapudi Murali Krishna wrote:have you tried?

Yes it works now

@Anshul Agrawal Thanks!Appreciate the quick response
Scott Selikoff
Saloon Keeper

Joined: Oct 23, 2005
Posts: 3753

As a side note, I really dislike reading code that uses integers for result sets, such as rs.getString(1). Name your projection variables, even if they are aggregate functions! Using rs.getInt("COUNT") is so much more illustrative.

There are so many reasons integer indexes can be bad, I'll let you guys fill in the blanks...

[OCA 8 Book] [Blog]
Neena Rangnani

Joined: Sep 23, 2009
Posts: 3
Hi Scott,

The one reason I can explain is If we use integer numbers to access columns , in that case if the table is altered later on (any column is deleted or appended) , then at every place in code there is need to modify numbered projections.

however if we use named projection variable , there is no impact on existing code. Only need to alter relevant code for(deleted/new column).

Let me know if you have anything to add up.

(New Member)
subject: Accessing data in ResultSet object
It's not a secret anymore!