java ResultSet,使用MAX sql函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1530108/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:53:09  来源:igfitidea点击:

java ResultSet, using MAX sql function

javasqldatabasejdbc

提问by Hellnar

Hello here is what I want, I connect to a DB and retrieve the biggest element of the UniqueId column, and assign it to an integer variable named maxID, here is my approach:

你好,这是我想要的,我连接到一个数据库并检索 UniqueId 列的最大元素,并将其分配给一个名为 maxID 的整数变量,这是我的方法:

int maxID = 0;
Statement s2 = con.createStatement();
s2.execute("SELECT MAX(UniqueId) FROM MyTable");    
ResultSet rs2 = s2.getResultSet(); // 
while ( rs2.next() ){
  maxID = rs2.getInt(0);
}

What would be a decent way of solving this, it feels like a very crude way by using "rs2.next()" while loop.

解决这个问题的好方法是什么,使用“rs2.next()”while 循环感觉像是一种非常粗糙的方法。

Thanks

谢谢

采纳答案by Boris Pavlovi?

if (rs2.next()) {
  maxID = rs2.getInt(1);
}

回答by Juparave

.next() is to reposition your cursor from 'nowhere' to a row if any.

.next() 是将光标从“无处”重新定位到一行(如果有)。

you can test it if you like, it is recommendable though that you do, so can't escape that while loop. Although if you're certain that the query will only return a single row, you can do this

如果你愿意,你可以测试它,虽然你这样做是值得推荐的,所以不能逃避那个 while 循环。虽然如果您确定查询只会返回一行,您可以这样做

if (rs.next()) {
   maxID = rs2.getInt(1);
}

回答by Bombe

Boris Pavlovi?was almost right.

鲍里斯·帕夫洛维?几乎是对的。

if (rs2.next()) {
  maxID = rs2.getInt(1);
}

The columns in a result set are 1-based. And the reason for using ifinstead of whileis that the query you're executing only returns a single row.

结果集中的列从 1 开始。使用if而不是的原因while是您正在执行的查询只返回一行。