How to get max id from database table in java code

I want to write code that gives max id from a table, but it throws an error.

the code:

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("XXXXX", "XXXX", "XXX");
Statement st2 = con.createStatement();
ResultSet idMax = st2.executeQuery("select nvl(max(work_id),0) from workdetails");
int id2 = idMax.getInt(0);  // throw error: Invalid column index

System.out.println(id2);

// ****************************
int id2 = idMax.getInt("work_id");
System.out.println(id2);   // throw error: ResultSet.next was not called
+5
source share
2 answers

The result set begins with a dummy record and must be transferred to the real first record by calling the method next:

ResultSet idMax = st2.executeQuery("select nvl(max(work_id),0) max_id from workdetails");
int id2 = -1;
if (idMax.next()) {
   id2 = idMax.getInt("max_id");  
}
+7
source

you skipped it

idMax.next();

This will set the pointer to the first line. Then only you should use

idMax.get ( 1 ); 

So your code is as follows:

ResultSet idMax = st2.executeQuery("select nvl(max(work_id),0) from workdetails");
int id2 = 0; 
if ( idMax.next() ){
   id2 = idMax.getInt(1);  
}
System.out.println(id2);
+2
source

All Articles