0

I want to be able to get check to see if there is a result in my resultset. Todo this i would execute:

if(rs.next()){
    boolean = true;
}

However i want to check to see if the value is in the database if so retrieve it:

while(rs.next())
     id = rs.getInt("id);

How would i go about combining the two? I want -2 to be returned if the resultset is empty.
Thanks in Advance,
Dean

Dean
  • 8,668
  • 17
  • 57
  • 86

2 Answers2

5
id = rs.next() ? rs.getInt("id") : -2;

like that?

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • Can you please explain this as i have never seen something written like this? – Dean Jun 02 '10 at 17:01
  • @Dean: it's a ternary expression with the ternary operator `?:`. It does basically the same as `int id; if (rs.next()) id = rs.getInt("id"); else id = -2;`. Also see http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op2.html – BalusC Jun 02 '10 at 17:06
2

Just use an if-else:

if (resultSet.next()) {
    return resultSet.getInt("id");
} else {
    return -2;
}

Also see this answer for more hints how to handle existence, zero/one, zero/more results.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Except you really should close the result set, which pretty much requires you to save the result in either case, then close the result set, then return. – Jay Jun 02 '10 at 17:17
  • 1
    @Jay: I don't know how you close your resources, but I usually close them in `finally` and it will just work fine. – BalusC Jun 02 '10 at 17:19
  • Okay, I'll buy that. Personally I usually close my connections in a finally block but close ResultSets and Statements in main-line code because I'm too lazy to declare them outside the try block and then populate them inside. – Jay Jun 03 '10 at 17:22