这不应该是一个非常简单的操作吗?但是,我看到既没有size()
也没有length()
方法.
请SELECT COUNT(*) FROM ...
改为查询.
要么
int size =0; if (rs != null) { rs.last(); // moves cursor to the last row size = rs.getRow(); // get row id }
在任何一种情况下,您都不必遍历整个数据.
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 }
好吧,如果你有一个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
使用时我遇到了异常 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++; }