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.

1
  • 2
    Longer answer: YES! Commented Jan 31, 2014 at 10:03

1 Answer 1

6

How about:

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

It doesn't save you much though

Sign up to request clarification or add additional context in comments.

5 Comments

I wouldn't return 0. I'd throw an exception to demonstrate something went wrong while obtaining the row value. No response != no rows.
Possibly, but I'd leave that to the developer. It depends on his expectations of the call.
I guess -1 might be a sensible value if you want to avoid exceptions. That's a classic "something is amiss" value.
Ok, agree on that. It does make sense to indicate that we couldn't get an answer
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.