如何从结果集中获取计数?

时间:2015-01-23 19:16:56

标签: java sql resultset

ResultSet rs = statement.executeQuery("SELECT COUNT(DISTINCT `id`) FROM `users`");
在MySQL中我已回答“5”,如何从java中的结果集中得到这个5?中间体

2 个答案:

答案 0 :(得分:2)

将其作为int列:

int count = -1;
if (rs.next()) {
    count = rs.getInt(1);
}

答案 1 :(得分:1)

尝试别名COUNT(DISTINCT ID),然后从ResultSet中检索别名。如果您最终在以后向查询添加更多逻辑,那么这将更易读并且更易于维护。

ResultSet rs = statement.executeQuery("SELECT COUNT(DISTINCT `id`) as NUM_ROWS FROM `users`");

int count = -1;
if(rs.next())
{
    count = rs.getInt("NUM_ROWS");

}