MySQL的JDBC判断查询结果是否为空以及获取查询结果行数的方法
来源:互联网 发布:淘宝怎样退换货 编辑:程序博客网 时间:2024/04/30 07:45
判断查询结果是否为空
在JDBC中没有方法hasNext去判断是否有下一条数据,但是我们可以使用next方法来代替。
看next方法的官方解释:
boolean next() throws
Moves the cursor forward one row from its current position. AResultSet
cursor is initially positioned before the first row; the first call to the methodnext
makes the first row the current row; the second call makes the second row the current row, and so on.When a call to the
next
method returnsfalse
, the cursor is positioned after the last row. Any invocation of aResultSet
method which requires a current row will result in aSQLException
being thrown. If the result set type isTYPE_FORWARD_ONLY
, it is vendor specified whether their JDBC driver implementation will returnfalse
or throw anSQLException
on a subsequent call tonext
.If an input stream is open for the current row, a call to the method
next
will implicitly close it. AResultSet
object's warning chain is cleared when a new row is read.- Returns:
true
if the new current row is valid;false
if there are no more rows- Throws:
SQLException
- if a database access error occurs or this method is called on a closed result set
boolean next() throws SQLException
将当前行从上一行移到下一行。一个 ResultSet的当前行最初指向第一行查询结果前。当第一次调用next的时候,当前行将会指向第一行查询结果。第二次调用就会指向第二行查询结果,等等。
当调用next方法返回false的时候,当前行当前行指向最后一行查询结果之后。这时候,任何
ResultSet
的请求当前行的方法调用都会导致SQLException
被抛出。但如果查询的结果设置为TYPE_FORWARD_ONLY,next方法在这时候根据实现厂商的不同,可能会返回false也坑能会抛出SQLException
异常 的警告将会被清楚。
关于的next的开始和结束,可以用下面的图来解释:
0->1->2->3->4->0 中间的1, 2, 3, 4是查询结果
^ ^
开始 结束
判断JDBC查询结果是否为空的正确姿势:
Statement statement = conn.createStatement();ResultSet res = statement.executeQuery(selectSql);if (!res.next()) { //res is null} else { // res is not null}
获取查询结果的行数
JDBC并没有直接提供获取查询结果总行数的方法给我们调用,为此我们需要使用间接的手段来执行:
第一种方法:
ResultSet res = ...使用某种方法获取查询结果int nRow = 0;while(res.next()) { ++nRow;}res.beforeFirst();// 其他代码不变
第二种方法:
ResultSet res = ...使用某种方法获取查询结果res.last();final int nRow = res.getRow();res.beforeFirst();// 其他代码不变
0 0
- MySQL的JDBC判断查询结果是否为空以及获取查询结果行数的方法
- 判断php查询出来的mysql结果是否为空
- 判断一个查询的结果是否为空
- 查询的结果集是否为空如何判断
- 判断查询结果是否为空
- 在PL/SQL中怎样判断查询的结果是否为空
- 关于数据库查询结果ResultSet判断是否为空的小知识点
- php如何判断SQL语句的查询结果是否为空?
- JDBC编程中,结果集为空的判断方法
- Mysql查询中文结果集为空的问题
- mysql将查询结果为空的栏目转为0
- UITableView 查询结果为空,显示无数据的方法
- 如何查询“直接查询结果为空”的视图
- 如何查询“直接查询结果为空”的视图
- 获取SQL查询结果集中的行数和列数
- mysql存储过程判断不为空和不为空,查询结果赋值变量
- sql语句查询怎么判断查询结果为空?
- 判断java,jdbc中ResultSet结果集是否为空
- 新手学习wpf记录 button上篇 等级3
- android中的线程池的使用
- jvm command 小计
- leetcode 17. Letter Combinations of a Phone Number
- MySql的常用命令和增删改查语句和数据类型
- MySQL的JDBC判断查询结果是否为空以及获取查询结果行数的方法
- COM组件调用过程
- python遍历字典所有的字段
- Silverlight中非对称加密及数字签名RSA算法的实现
- Quartz 触发器(SimpleTrigger&CronTrigger )配置说明 & cronExpression表达式
- POJ_3281_Dining && NYOJ _326_Dining
- const,static,extern简介
- iOS UIAlertController
- 两个链表相交的节点