oracle 如何从java代码中的数据库表中获取Max id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10929918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Max id from table of database in java code
提问by Vinit Vikash
I want to write code which give max id from the table but it is throwing error.
我想编写从表中给出最大 id 的代码,但它抛出错误。
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
回答by giorashc
A result set starts at a dummy record and should be advanced to the real first record by calling the next
method :
结果集从一个虚拟记录开始,应该通过调用以下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");
}
回答by Rakesh Juyal
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);