tags:

views:

102

answers:

2

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

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

like that?

skaffman
Can you please explain this as i have never seen something written like this?
Dean
@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
+2  A: 

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.

BalusC
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
@Jay: I don't know how you close your resources, but I usually close them in `finally` and it will just work fine.
BalusC
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