How to get Max id from table of database in java code

15,683

Solution 1

A result set starts at a dummy record and should be advanced to the real first record by calling the next method :

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");  
}

Solution 2

You missed

idMax.next();

This will set the pointer to the first row. Then only you have to use

idMax.get ( 1 ); 

So, your code goes like this:

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);
Share:
15,683
Vinit ...
Author by

Vinit ...

Development Engineer

Updated on June 09, 2022

Comments

  • Vinit ...
    Vinit ... almost 2 years

    I want to write code which give max id from the table but it is throwing error.

    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