如何在java代码中从数据库表中获取Max id

时间:2012-06-07 10:21:42

标签: java sql database oracle

我想编写从表中提供最大id的代码但是它会抛出错误。

代码:

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 个答案:

答案 0 :(得分:7)

结果集从虚拟记录开始,应通过调用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");  
}

答案 1 :(得分:2)

你错过了

idMax.next();

这会将指针设置为第一行。那么只有你必须使用

idMax.get ( 1 ); 

所以,你的代码是这样的:

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