java ResultSet, using MAX sql function
26,289
Solution 1
if (rs2.next()) {
maxID = rs2.getInt(1);
}
Solution 2
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.
Solution 3
.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);
}
Author by
Hellnar
Updated on July 18, 2022Comments
-
Hellnar almost 2 years
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
-
Hellnar over 14 yearsseems like a good idea but, when I change as above Eclipse is displaying this error: Description Resource Path Location Type Cannot invoke getInt(int) on the primitive type boolean Alertmail.java /alertmail/src line 33 Java Problem
-
akf over 14 yearsyes,
next()
returns a boolean, and therefore works in thewhile()
loop. -
Juparave over 14 yearsyes, 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
-
Boris Pavlović over 14 yearsI've just fixed mine answer and gave you +1