从 ResultSet 中获取行数

Get the number of rows from ResultSet

我正在尝试获取我从查询中获取的 ResultSet 中的数字,如下面的代码所示。查询检索数字 5。如何从 ResultSet 中获取此数字?

代码:

String sql_count_stop = "select count(*) FROM behaviour where  mac = ? ";
PreparedStatement preparedCount = con.prepareStatement(sql_count_stop);
preparedCount.setString(1, macD);
ResultSet rsCount = preparedCount.executeQuery();
while(rsCount.next()){

}

您可以将查询修改为

"SELECT count(*) AS totalCount FROM behaviour WHERE mac = ? ";

然后使用,

macId= rsCount.getInt("totalCount");

您可以将 SQL 语句修改为:(添加 AS 'countMacs'

select count(*) as 'countMacs' FROM behaviour where  mac = ? 

然后得到一个值

while(rsCount.next()){
  int count = rsCount.getInt("countMacs");
}

或者使用位置 rsCount.getInt(1) 并且您不需要列别名。

此外,由于只有一行,if(rsCount.next())while 一样好,而且在我看来更清楚地表明此逻辑只会执行一次。