s5s
s5s

Reputation: 12134

Java JDBC: Do I need to loop ResultSet when query returns single row?

My sql query returns one row only. When querying, do I need to follow the usual while(rs.next) {...} pattern or can I do:

...
rs.next();
int id  = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
...

Instead of:

...
      while(rs.next()){
         //Retrieve by column name
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");
      }
...

Upvotes: 2

Views: 6508

Answers (2)

L.Spillner
L.Spillner

Reputation: 1772

No you don't have to loop every time since the call of rs.next() already sets the pointer from null to the first available row and returns wheather there is an entry or not.

Still it makes sense to check if something was returned at all:

if(rs.next())
{
    // process resultset
}else
{
    // do something when no data arrived
}

Upvotes: 4

Poshi
Poshi

Reputation: 5762

You can avoid the use of the loop if you are only interested on the first result (or there is only one). It would also be a good practice if you make sure you got some result:

...
if (rs.next()) {
    int id  = rs.getInt("id");
    int age = rs.getInt("age");
    String first = rs.getString("first");
    String last = rs.getString("last");
}
...

In any case, don't forget to close the resources no longer used (ResultSet, Statement, Connection...)

Upvotes: 0

Related Questions