7

我想编写从表中给出最大 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
4

2 回答 2

8

结果集从一个虚拟记录开始,应该通过调用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");  
}
于 2012-06-07T10:24:19.923 回答
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);
于 2012-06-07T10:30:43.883 回答