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

时间:2008-10-10 16:12:46

标签: java sql jdbc resultset record-count

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

15 个答案:

答案 0 :(得分:249)

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

OR

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

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

答案 1 :(得分:81)

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
}

答案 2 :(得分:19)

好吧,如果您的ResultSet类型为ResultSet.TYPE_FORWARD_ONLY,您希望保持这种方式(并且>切换为ResultSet.TYPE_SCROLL_INSENSITIVE或{{ 1}}以便能够使用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]

答案 3 :(得分:12)

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

答案 4 :(得分:10)

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

答案 5 :(得分:4)

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

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

答案 6 :(得分:3)

获取ResultSet大小的方法,不需要使用ArrayList等

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

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

rs.beforeFirst();  

答案 7 :(得分:3)

[速度考虑]

这里的很多人建议使用ResultSet.last(),但为此你需要打开连接作为ResultSet.TYPE_SCROLL_INSENSITIVE,对于Derby嵌入式数据库来说,最多10次 SLOWER 而不是{{ 1}}。

根据我对嵌入式Derby和H2数据库的微测试,在SELECT之前调用ResultSet.TYPE_FORWARD_ONLY要快得多。

Here is in more detail my code and my benchmarks

答案 8 :(得分:1)

我检查了 ResultSet 界面的运行时值,发现它几乎都是 ResultSetImpl 。 ResultSetImpl有一个名为getUpdateCount()的方法,它返回您要查找的值。

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

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

答案 9 :(得分: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);

     }

答案 10 :(得分:1)

今天,我用这个逻辑为什么我不知道得到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.

答案 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)

我遇到了同样的问题。在执行解决后以这种方式使用ResultSet.first()

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

文档(link):

boolean first()
    throws SQLException
     

将光标移动到此ResultSet对象的第一行。

     

退货:

     

true如果光标处于有效状态   行; false如果结果集中没有行

     

投掷:

     

SQLException - 如果发生数据库访问错误;在闭合的结果集上调用此方法,或者结果集类型为TYPE_FORWARD_ONLY

     

SQLFeatureNotSupportedException - 如果JDBC驱动程序不支持   这个方法

     

<强>时间:

     

1.2

答案 13 :(得分:0)

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

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

答案 14 :(得分:-1)

为列命名..

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.");
    }
}