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

时间:2023-02-11 11:52:52

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

这不是一个很简单的操作吗?但是,我看到没有一个size()和length()方法。

14 个解决方案

#1


232  

resultSet.last() followed by resultSet.getRow() will give you the row count, but it may not be a good idea as it can mean reading the entire table over the network and throwing away the data. Do a SELECT COUNT(*) FROM ... query instead.

最后的结果()后面是resultSet.getRow(),它会给你行数,但这可能不是一个好主意,因为它意味着在网络上读取整个表并扔掉数据。从…中选择COUNT(*)查询。

#2


76  

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
}

#3


17  

Well, if you have a ResultSet of type ResultSet.TYPE_FORWARD_ONLY you want to keep it that way (and not to switch to a ResultSet.TYPE_SCROLL_INSENSITIVE or ResultSet.TYPE_SCROLL_INSENSITIVE in order to be able to use .last()).

如果你有一个ResultSet的结果集。TYPE_FORWARD_ONLY你想要保持这种方式(不要切换到ResultSet)。TYPE_SCROLL_INSENSITIVE或结果集。type_scroll_迟钝,以便能够使用.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

#4


10  

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

#5


9  

I got an exception when using rs.last()

我在使用rs的时候有一个例外。

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

#6


4  

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

#7


3  

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

计算结果集大小的方法,不需要使用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,

现在您将获得大小,如果您想要打印ResultSet,在打印使用以下代码行之前,

rs.beforeFirst();  

#8


2  

[Speed consideration]

(速度考虑)

Lot of ppl here suggests ResultSet.last() but for that you would need to open connection as a ResultSet.TYPE_SCROLL_INSENSITIVE which for Derby embedded database is up to 10 times SLOWER than ResultSet.TYPE_FORWARD_ONLY.

这里的许多ppl都显示了ResultSet.last(),但是您需要打开连接作为ResultSet。对于Derby嵌入式数据库,type_scroll_迟钝的速度比ResultSet.TYPE_FORWARD_ONLY慢10倍。

According to my micro-tests for embedded Derby and H2 databases it is significantly faster to call SELECT COUNT(*) before your SELECT.

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

Here is in more detail my code and my benchmarks

下面是我的代码和基准。

#9


1  

I checked the runtime value of the ResultSet interface and found out it was pretty much a ResultSetImpl all 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);双rowCount =((ResultSetImpl)结果集).getUpdateCount()

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

我知道downcasting通常是一个不安全的过程,但是这个方法还没有让我失望。

#10


1  

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

     }

#11


0  

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

#12


0  

I was having the same problem. Using ResultSet.first() in this way just after the execution solved it:

我也有同样的问题。使用ResultSet.first(),在执行解决之后:

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

Documentation (link):

文档(链接):

boolean first()
    throws SQLException

Moves the cursor to the first row in this ResultSet object.

将光标移到这个ResultSet对象的第一行。

Returns:

返回:

true if the cursor is on a valid row; false if there are no rows in the result set

如果游标在有效行上,则为真;如果结果集中没有行,则为false。

Throws:

抛出:

SQLException - if a database access error occurs; this method is called on a closed result set or the result set type is TYPE_FORWARD_ONLY

SQLException -如果发生数据库访问错误;这个方法被调用在一个封闭的结果集上,或者结果集类型是TYPE_FORWARD_ONLY。

SQLFeatureNotSupportedException - if the JDBC driver does not support this method

如果JDBC驱动程序不支持此方法,则SQLFeatureNotSupportedException。

Since:

自:

1.2

1.2

#13


0  

Today, I used this logic why I don't know getting the count of RS.

今天,我用这个逻辑来解释为什么我不知道如何计算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.

#14


-3  

Similar to Garret's method,

类似于阁楼的方法,

boolean isEmpty = true
while(rs.next()){
    isEmpty = false;
    //do stuff here
}

Nice and simple, and we don't have a potentially giant integer being generated. This of course assumes we want to iterate over our result set. If we don't want to iterate over it, then doing a count should suffice.

很好很简单,我们没有生成一个潜在的巨大整数。这当然假设我们希望迭代结果集。如果我们不想迭代它,那么做一个计数就足够了。

#1


232  

resultSet.last() followed by resultSet.getRow() will give you the row count, but it may not be a good idea as it can mean reading the entire table over the network and throwing away the data. Do a SELECT COUNT(*) FROM ... query instead.

最后的结果()后面是resultSet.getRow(),它会给你行数,但这可能不是一个好主意,因为它意味着在网络上读取整个表并扔掉数据。从…中选择COUNT(*)查询。

#2


76  

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
}

#3


17  

Well, if you have a ResultSet of type ResultSet.TYPE_FORWARD_ONLY you want to keep it that way (and not to switch to a ResultSet.TYPE_SCROLL_INSENSITIVE or ResultSet.TYPE_SCROLL_INSENSITIVE in order to be able to use .last()).

如果你有一个ResultSet的结果集。TYPE_FORWARD_ONLY你想要保持这种方式(不要切换到ResultSet)。TYPE_SCROLL_INSENSITIVE或结果集。type_scroll_迟钝,以便能够使用.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

#4


10  

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

#5


9  

I got an exception when using rs.last()

我在使用rs的时候有一个例外。

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

#6


4  

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

#7


3  

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

计算结果集大小的方法,不需要使用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,

现在您将获得大小,如果您想要打印ResultSet,在打印使用以下代码行之前,

rs.beforeFirst();  

#8


2  

[Speed consideration]

(速度考虑)

Lot of ppl here suggests ResultSet.last() but for that you would need to open connection as a ResultSet.TYPE_SCROLL_INSENSITIVE which for Derby embedded database is up to 10 times SLOWER than ResultSet.TYPE_FORWARD_ONLY.

这里的许多ppl都显示了ResultSet.last(),但是您需要打开连接作为ResultSet。对于Derby嵌入式数据库,type_scroll_迟钝的速度比ResultSet.TYPE_FORWARD_ONLY慢10倍。

According to my micro-tests for embedded Derby and H2 databases it is significantly faster to call SELECT COUNT(*) before your SELECT.

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

Here is in more detail my code and my benchmarks

下面是我的代码和基准。

#9


1  

I checked the runtime value of the ResultSet interface and found out it was pretty much a ResultSetImpl all 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);双rowCount =((ResultSetImpl)结果集).getUpdateCount()

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

我知道downcasting通常是一个不安全的过程,但是这个方法还没有让我失望。

#10


1  

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

     }

#11


0  

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

#12


0  

I was having the same problem. Using ResultSet.first() in this way just after the execution solved it:

我也有同样的问题。使用ResultSet.first(),在执行解决之后:

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

Documentation (link):

文档(链接):

boolean first()
    throws SQLException

Moves the cursor to the first row in this ResultSet object.

将光标移到这个ResultSet对象的第一行。

Returns:

返回:

true if the cursor is on a valid row; false if there are no rows in the result set

如果游标在有效行上,则为真;如果结果集中没有行,则为false。

Throws:

抛出:

SQLException - if a database access error occurs; this method is called on a closed result set or the result set type is TYPE_FORWARD_ONLY

SQLException -如果发生数据库访问错误;这个方法被调用在一个封闭的结果集上,或者结果集类型是TYPE_FORWARD_ONLY。

SQLFeatureNotSupportedException - if the JDBC driver does not support this method

如果JDBC驱动程序不支持此方法,则SQLFeatureNotSupportedException。

Since:

自:

1.2

1.2

#13


0  

Today, I used this logic why I don't know getting the count of RS.

今天,我用这个逻辑来解释为什么我不知道如何计算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.

#14


-3  

Similar to Garret's method,

类似于阁楼的方法,

boolean isEmpty = true
while(rs.next()){
    isEmpty = false;
    //do stuff here
}

Nice and simple, and we don't have a potentially giant integer being generated. This of course assumes we want to iterate over our result set. If we don't want to iterate over it, then doing a count should suffice.

很好很简单,我们没有生成一个潜在的巨大整数。这当然假设我们希望迭代结果集。如果我们不想迭代它,那么做一个计数就足够了。