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


ResultSet rs = ps.executeQuery();
int rowcount = 0;
if (rs.last()) {
  rowcount = rs.getRow();
  rs.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element
}
while (rs.next()) {
  // do your standard per row stuff
}

SELECT COUNT(*) FROM…查询。

OR

int size =0;
if (rs != null) 
{
  rs.last();    // moves cursor to the last row
  size = rs.getRow(); // get row id 
}

在这两种情况下,都不需要遍历整个数据。


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

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

当使用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); 

theStatement=theConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

ResultSet theResult=theStatement.executeQuery(query); 

//Get the size of the data returned
theResult.last();     
int size = theResult.getRow() * theResult.getMetaData().getColumnCount();       
theResult.beforeFirst();

如果你有一个ResultSet类型的ResultSet。TYPE_FORWARD_ONLY您希望保持这种方式(而不是切换到ResultSet)。TYPE_SCROLL_INSENSITIVE或ResultSet。TYPE_SCROLL_INSENSITIVE,以便能够使用.last())。

我建议一种非常有效的破解方法,即在顶部添加第一个包含行数的伪/伪行。

例子

假设您的查询如下

select MYBOOL,MYINT,MYCHAR,MYSMALLINT,MYVARCHAR
from MYTABLE
where ...blahblah...

输出是这样的

true    65537 "Hey" -32768 "The quick brown fox"
false  123456 "Sup"    300 "The lazy dog"
false -123123 "Yo"       0 "Go ahead and jump"
false       3 "EVH"    456 "Might as well jump"
...
[1000 total rows]

简单地重构你的代码,就像这样:

Statement s=myConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY,
                                         ResultSet.CONCUR_READ_ONLY);
String from_where="FROM myTable WHERE ...blahblah... ";
//h4x
ResultSet rs=s.executeQuery("select count(*)as RECORDCOUNT,"
                           +       "cast(null as boolean)as MYBOOL,"
                           +       "cast(null as int)as MYINT,"
                           +       "cast(null as char(1))as MYCHAR,"
                           +       "cast(null as smallint)as MYSMALLINT,"
                           +       "cast(null as varchar(1))as MYVARCHAR "
                           +from_where
                           +"UNION ALL "//the "ALL" part prevents internal re-sorting to prevent duplicates (and we do not want that)
                           +"select cast(null as int)as RECORDCOUNT,"
                           +       "MYBOOL,MYINT,MYCHAR,MYSMALLINT,MYVARCHAR "
                           +from_where);

您的查询输出将如下所示

1000 null     null null    null null
null true    65537 "Hey" -32768 "The quick brown fox"
null false  123456 "Sup"    300 "The lazy dog"
null false -123123 "Yo"       0 "Go ahead and jump"
null false       3 "EVH"    456 "Might as well jump"
...
[1001 total rows]

所以你必须

if(rs.next())
    System.out.println("Recordcount: "+rs.getInt("RECORDCOUNT"));//hack: first record contains the record count
while(rs.next())
    //do your stuff

我检查了ResultSet接口的运行时值,发现它几乎一直都是一个ResultSetImpl。ResultSetImpl有一个名为getUpdateCount()的方法,它返回您正在寻找的值。

下面的代码示例应该足够了: ResultSet ResultSet = executeQuery(sqlQuery); double rowCount = ((ResultSetImpl)resultSet).getUpdateCount()

我知道向下转换通常是一个不安全的过程,但这个方法还没有让我失败。


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);

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

获取ResultSet大小的方法,不需要使用数组列表等

int size =0;  
if (rs != null)   
{  
rs.beforeFirst();  
 rs.last();  
size = rs.getRow();
}

现在你会得到大小,如果你想打印ResultSet,在打印之前使用以下一行代码,

rs.beforeFirst();  

我也有同样的问题。以这种方式使用ResultSet.first()在执行后解决它:

if(rs.first()){
    // Do your job
} else {
    // No rows take some actions
}

文档(链接):

布尔第一次() 抛出SQLException异常 将光标移动到此ResultSet对象的第一行。 返回: 如果光标位于有效的 行;如果结果集中没有行,则为False 抛出: SQLException—如果发生数据库访问错误;在封闭的结果集或结果集类型为TYPE_FORWARD_ONLY时调用此方法 SQLFeatureNotSupportedException—如果JDBC驱动程序不支持 这个方法 自: 1.2


(速度考虑)

很多人在这里建议ResultSet.last(),但你需要打开连接作为一个ResultSet。TYPE_SCROLL_INSENSITIVE,对于Derby嵌入式数据库,它比ResultSet.TYPE_FORWARD_ONLY慢10倍。

根据我对嵌入式Derby和H2数据库的微型测试,在SELECT之前调用SELECT COUNT(*)要快得多。

下面是我的代码和基准测试的更详细信息


今天,我用了这个逻辑,为什么我不知道得到RS的计数。

int chkSize = 0;
if (rs.next()) {
    do {  ..... blah blah
        enter code here for each rs.
        chkSize++;
    } while (rs.next());
} else {
    enter code here for rs size = 0 
}
// good luck to u.

为列命名。

String query = "SELECT COUNT(*) as count FROM

引用该列从ResultSet对象到int,并从那里做你的逻辑。

PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, item.getProductId());
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
    int count = resultSet.getInt("count");
    if (count >= 1) {
        System.out.println("Product ID already exists.");
    } else {
        System.out.println("New Product ID.");
    }
}

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

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