这不是一个很简单的手术吗?但是,我看到既没有size()也没有length()方法。


当前回答

int i = 0;
while(rs.next()) {
    i++;
}

其他回答

这是一种简单的行计数方法。

ResultSet rs = job.getSearchedResult(stmt);
int rsCount = 0;

//but notice that you'll only get correct ResultSet size after end of the while loop
while(rs.next())
{
    //do your other per row stuff 
    rsCount = rsCount + 1;
}//end while

最简单的方法,运行Count(*)查询,执行resultSet.next()指向第一行,然后执行resultSet.getString(1)获得计数。代码:

ResultSet rs = statement.executeQuery("Select Count(*) from your_db");
if(rs.next()) {
   int count = rs.getString(1).toInt()
}

当使用rs.last()时,我得到了一个异常

if(rs.last()){
    rowCount = rs.getRow(); 
    rs.beforeFirst();
}

:

java.sql.SQLException: Invalid operation for forward only resultset

因为默认情况下它是ResultSet。TYPE_FORWARD_ONLY,这意味着只能使用rs.next()

解决方案是:

stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY); 
int i = 0;
while(rs.next()) {
    i++;
}
String sql = "select count(*) from message";
ps =  cn.prepareStatement(sql);

rs = ps.executeQuery();
int rowCount = 0;
while(rs.next()) {
    rowCount = Integer.parseInt(rs.getString("count(*)"));
    System.out.println(Integer.parseInt(rs.getString("count(*)")));
}
System.out.println("Count : " + rowCount);