Java ResultSet using MAX sql function

Hi, this is what I want, I connect to the database and extract the largest element of the UniqueId column and assign it 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);
}

Whatever a decent way to solve this, it looks very rude using the rs2.next () while loop.

thanks

+5
source share
3 answers
if (rs2.next()) {
  maxID = rs2.getInt(1);
}
+10
source

Boris Pavlovich was almost right.

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

The columns in the result set are based on 1. And the reason for using ifinstead whileis because your query returns only one row.

+9
source

.next() - "" , .

you can check it if you want, it is recommended, although you do it, therefore you cannot avoid this while loop. Although, if you are sure that the query will return only one row, you can do it

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

All Articles