Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java ResultSet, using MAX sql function

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

like image 861
Hellnar Avatar asked Oct 07 '09 07:10

Hellnar


People also ask

What is SQL ResultSet in Java?

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).

How to get INT from a resultset in Java?

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.

How many columns are in a resultset in Java?

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.

How to calculate the greatest maximum value of SQL numbers?

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.


1 Answers

if (rs2.next()) {
  maxID = rs2.getInt(1);
}
like image 95
Boris Pavlović Avatar answered Sep 19 '22 21:09

Boris Pavlović