1

I have a simple query that returns only count of rows.

select count(*) cnt from table

I can read it by iterating through resultset.

like

while(rs.next()){
  int rowCount= rs.getInt(cnt);
}

But is there any way,using which I can get count directly without looping.

Not a bug
  • 4,286
  • 2
  • 40
  • 80
Ninad Pingale
  • 6,801
  • 5
  • 32
  • 55

1 Answers1

6

How about:

int rowCount = rs.next() ? rs.getInt(cnt) : -1;

It doesn't save you much though

mikea
  • 6,537
  • 19
  • 36
  • 1
    I wouldn't return `0`. I'd throw an exception to demonstrate something went wrong while obtaining the row value. No response != no rows. – Duncan Jones Jan 31 '14 at 09:48
  • 1
    Possibly, but I'd leave that to the developer. It depends on his expectations of the call. – mikea Jan 31 '14 at 09:49
  • 2
    I guess `-1` might be a sensible value if you want to avoid exceptions. That's a classic "something is amiss" value. – Duncan Jones Jan 31 '14 at 09:51
  • 1
    Ok, agree on that. It does make sense to indicate that we couldn't get an answer – mikea Jan 31 '14 at 09:55
  • 1
    It doesn't save much indeed, but it is a lot cleaner. When you select a count, it is a safe assumption there is one row. – Gimby Jan 31 '14 at 10:00