如何获得 java.sql.ResultSet 的大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/192078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:08:11  来源:igfitidea点击:

How do I get the size of a java.sql.ResultSet?

javasqljdbcresultsetrecord-count

提问by Jake

Shouldn't this be a pretty straightforward operation? However, I see there's neither a size()nor length()method.

这不应该是一个非常简单的操作吗?但是,我看到既没有size()也没有length()方法。

采纳答案by finnw

Do a SELECT COUNT(*) FROM ...query instead.

SELECT COUNT(*) FROM ...改为进行查询。

OR

或者

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

In either of the case, you won't have to loop over the entire data.

在任何一种情况下,您都不必遍历整个数据。

回答by JeeBee

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
}

回答by CounterSpell

It is a simple way to do rows-count.

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

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

回答by Dan

I got an exception when using rs.last()

使用时出现异常 rs.last()

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

:

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

it's due to by default it is ResultSet.TYPE_FORWARD_ONLY, which means you can only use rs.next()

这是由于默认情况下它是ResultSet.TYPE_FORWARD_ONLY,这意味着您只能使用rs.next()

the solution is:

解决办法是:

stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY); 

回答by Ben

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

回答by Unai Vivi

Well, if you have a ResultSetof type ResultSet.TYPE_FORWARD_ONLYyou want to keep it that way (and notto switch to a ResultSet.TYPE_SCROLL_INSENSITIVEor ResultSet.TYPE_SCROLL_INSENSITIVEin order to be able to use .last()).

好吧,如果您有 aResultSet类型,ResultSet.TYPE_FORWARD_ONLY您希望保持这种方式(而不是切换到 aResultSet.TYPE_SCROLL_INSENSITIVEResultSet.TYPE_SCROLL_INSENSITIVE为了能够使用.last())。

I suggest a very nice and efficient hack, where you add a first bogus/phony row at the top containing the number of rows.

我建议一个非常好的和有效的 hack,你在顶部添加一个包含行数的第一个假/假行。

Example

例子

Let's say your query is the following

假设您的查询如下

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

and your output looks like

你的输出看起来像

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]

Simply refactor your code to something like this:

只需将您的代码重构为如下所示:

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

Your query output will now be something like

您的查询输出现在将类似于

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]

So you just have to

所以你只需要

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

回答by clausavram

I checked the runtime value of the ResultSetinterface and found out it was pretty much a ResultSetImplall the time. ResultSetImpl has a method called getUpdateCount()which returns the value you are looking for.

我检查了ResultSet接口的运行时值,发现它几乎一直是一个ResultSetImpl。ResultSetImpl 有一个被调用的方法getUpdateCount(),它返回您要查找的值。

This code sample should suffice:
ResultSet resultSet = executeQuery(sqlQuery);
double rowCount = ((ResultSetImpl)resultSet).getUpdateCount()

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

I realize that downcasting is generally an unsafe procedure but this method hasn't yet failed me.

我意识到向下转型通常是一个不安全的过程,但这种方法还没有让我失望。

回答by Peter.Chu

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

回答by bhaskar

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

回答by Anptk

The way of getting size of ResultSet, No need of using ArrayList etc

ResultSet大小的获取方式,无需使用ArrayList等

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

Now You will get size, And if you want print the ResultSet, before printing use following line of code too,

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

rs.beforeFirst();