7

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

2 Answers 2

8

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");  
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.