前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【JDBC】JDBC API 详解 ④ ( ResultSet 查询结果对象 | 移动光标函数 | 获取数据函数 | ResultSet 代码示例 )

【JDBC】JDBC API 详解 ④ ( ResultSet 查询结果对象 | 移动光标函数 | 获取数据函数 | ResultSet 代码示例 )

作者头像
韩曙亮
发布2023-03-25 11:44:48
6960
发布2023-03-25 11:44:48
举报

文章目录

一、ResultSet 查询结果对象


ResultSet 查询结果对象 中 封装了 SQL 查询语句的 返回结果 , 执行下面的函数查询 数据库 , 返回的就是该对象 ;

代码语言:javascript
复制
    ResultSet executeQuery(String sql) throws SQLException;

1、移动光标函数

ResultSet 移动光标 : ResultSet 默认光标在第 1 行 , 每次调用 next 函数 , 都会移动光标到下一行 , 函数原型如下 :

代码语言:javascript
复制
	boolean next() throws SQLException;

该函数有 2 个作用

  • 将光标移动到下一行 ;
  • 判断移动后的光标指向的数据是否有效 ;

boolean 返回值 说明 :

  • 返回 true , 说明当前移动后的光标指向的数据行 , 数据是有效的 ;
  • 返回 false , 说明当前数据行是无效的 ;

2、获取数据函数

ResultSet 获取数据 : getXxx() 函数 获取一行数据中的指定列信息 ;

代码语言:javascript
复制
	String getString(int columnIndex) throws SQLException;
    boolean getBoolean(int columnIndex) throws SQLException;
    byte getByte(int columnIndex) throws SQLException;
    short getShort(int columnIndex) throws SQLException;
    int getInt(int columnIndex) throws SQLException;
    long getLong(int columnIndex) throws SQLException;
    float getFloat(int columnIndex) throws SQLException;

    String getString(String columnLabel) throws SQLException;
    boolean getBoolean(String columnLabel) throws SQLException;
    byte getByte(String columnLabel) throws SQLException;
    short getShort(String columnLabel) throws SQLException;

此类函数 , 参数有两种 :

  • int columnIndex : 列的编号 , 从 1 开始计数 ;
  • String columnLabel : 列的名称 ;

3、ResultSet 代码示例

ResultSet 代码示例 :

代码语言:javascript
复制
// 加载 JDBC 驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");

// 建立数据库连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");

// 创建 SQL 查询语句
String sql = "SELECT * FROM customers";

// 创建 PreparedStatement 对象并设置参数
PreparedStatement pstmt = conn.prepareStatement(sql);

// 执行查询操作并获取结果集
ResultSet rs = pstmt.executeQuery();

// 遍历结果集并处理数据
while (rs.next()) {
    // 获取每行数据中的各个列的值
    int id = rs.getInt("id");
    String name = rs.getString("name");
    String email = rs.getString("email");
    // 处理数据...
}

// 关闭 ResultSet、PreparedStatement 和 Connection 对象
rs.close();
pstmt.close();
conn.close();
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-03-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 一、ResultSet 查询结果对象
    • 1、移动光标函数
      • 2、获取数据函数
        • 3、ResultSet 代码示例
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档