java ResultSet,使用MAX sql函数

时间:2023-02-11 11:52:58

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:

你好,这就是我想要的,我连接到DB并检索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()”感觉就像一种非常粗糙的方式。

Thanks

谢谢

3 个解决方案

#1


12  

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

#2


10  

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 if instead of while is that the query you’re executing only returns a single row.

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

#3


1  

.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

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

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

#1


12  

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

#2


10  

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 if instead of while is that the query you’re executing only returns a single row.

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

#3


1  

.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

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

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