文章目录

  • 一、ResultSet 查询结果对象
  • 1、移动光标函数
  • 2、获取数据函数
  • 3、ResultSet 代码示例






一、ResultSet 查询结果对象



ResultSet 查询结果对象 中 封装了 SQL 查询语句的 返回结果

ResultSet executeQuery(String sql) throws SQLException;



1、移动光标函数



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

boolean next() throws SQLException;

该函数有 2 个作用

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

boolean 返回值 说明 :

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


2、获取数据函数



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

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 代码示例 :

// 加载 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();