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();
s开发者_如何学编程2.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
if (rs2.next()) {
maxID = rs2.getInt(1);
}
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.
.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);
}
精彩评论