views:

268

answers:

3

Hello here is what I want, I connect to a DB and retrieve the biggest element of the UniqueId column, and assign it to an integer variable named maxID, here is my approach:

int maxID = 0;
Statement s2 = con.createStatement();
s2.execute("SELECT MAX(UniqueId) FROM MyTable");    
ResultSet rs2 = s2.getResultSet(); // 
while ( rs2.next() ){
maxID = rs2.getInt(0);
}

What would be a decent way of solving this, it feels like a very crude way by using "rs2.next()" while loop.

Thanks

A: 

.next() is to reposition your cursor from 'nowhere' to a row if any.

you can test it if you like, it is recommendable though that you do, so can't escape that while loop. Although if you're certain that the query will only return a single row, you can do this

if (rs.next()) {
   maxID = rs2.getInt(1);
}
Juparave
seems like a good idea but, when I change as above Eclipse is displaying this error: Description Resource Path Location TypeCannot invoke getInt(int) on the primitive type boolean Alertmail.java /alertmail/src line 33 Java Problem
Hellnar
yes, `next()` returns a boolean, and therefore works in the `while()` loop.
akf
yes, Is right, you need to reposition the cursor before yo can fetch any data, I rushed my answer. I shouldn't be looking at questions this time of the night. I'm going to edit my answer
Juparave
I should had leave as it was...
Juparave
+3  A: 
if (rs2.next()) {
  maxID = rs2.getInt(1);
}
Boris Pavlović
+3  A: 

Boris Pavlović was almost right.

if (rs2.next()) {
  maxID = rs2.getInt(1);
}

The columns in a result set are 1-based. And the reason for using if instead of while is that the query you’re executing only returns a single row.

Bombe
I've just fixed mine answer and gave you +1
Boris Pavlović