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
The java.sql.ResultSet interface represents such tabular data returned by the SQL statements. i.e. the ResultSet object holds the tabular data returned by the methods that execute the statements which quires the database (executeQuery () method of the Statement interface in general).
For example, if the column you are interested in viewing contains an int, you need to use one of the getInt () methods of ResultSet − Returns the int in the current row in the column named columnName. Returns the int in the current row in the specified column index.
The column index starts at 1, meaning the first column of a row is 1, the second column of a row is 2, and so on. Similarly, there are get methods in the ResultSet interface for each of the eight Java primitive types, as well as common types such as java.lang.String, java.lang.Object, and java.net.URL.
Then the max function will internally compare each of their values and finally derive 200 as the greatest maximum value. Given below are the examples of SQL MAX (): Example #1 – Using a single column. Let us firstly consider a simple example that we used above. We will calculate the greatest value of SQL numbers using the MAX () function.
if (rs2.next()) {
maxID = rs2.getInt(1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With