MySQL的JDBC判断查询结果是否为空以及获取查询结果行数的方法_MySQL

php中文网
发布: 2016-06-08 08:50:40
原创
1771人浏览过

判断查询结果是否为空

在JDBC中没有方法hasNext去判断是否有下一条数据,但是我们可以使用next方法来代替。 看next方法的官方解释:
  • boolean next()
          throws 
    登录后复制
    Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next 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 returns false, the cursor is positioned after the last row. any invocation of a resultset method which requires a current row will result in a sqlexception being thrown. if the result set type is type_forward_only, it is vendor specified whether their jdbc driver implementation will return false or throw an sqlexception on a subsequent call to next.

    If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.

    MeDo
    MeDo

    无代码AI应用开发,百度秒哒海外版

    MeDo 126
    查看详情 MeDo
    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();
    // 其他代码不变
    登录后复制
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号