这不是一个很简单的手术吗?但是,我看到既没有size()也没有length()方法。
当前回答
我也有同样的问题。以这种方式使用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 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();
推荐文章
- Javadoc @see或{@link}?
- 在准备语句中使用“like”通配符
- Android Eclipse -无法找到*.apk
- javac和Eclipse编译器之间的区别是什么?
- 有人可以对SQL查询进行版权保护吗?
- 工厂模式和策略模式之间的区别是什么?
- 如何知道MySQL表最近一次更新?
- 在Java中使用正则表达式提取值
- 如何转储一些SQLite3表的数据?
- 如何创建一个SQL Server函数“连接”多行从一个子查询到一个单独的分隔字段?
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- 在MySQL中的一个查询中更新多个具有不同值的行
- Intellij IDEA Java类在保存时不能自动编译
- 何时使用Mockito.verify()?
- 在maven中安装mvn到底做什么