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
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");
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With