Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 827
Vinit ... Avatar asked Jun 07 '12 10:06

Vinit ...


2 Answers

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");  
}
like image 192
giorashc Avatar answered Oct 17 '22 22:10

giorashc


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);
like image 42
Rakesh Juyal Avatar answered Oct 17 '22 21:10

Rakesh Juyal