如何将结果集指针移动到所需位置?


ResultSet 接口的 absolute() 方法接受一个整数值,它表示某一行的索引,并且将当前 ResultSet 对象的 ResultSet 指针移动到指定位置。

假设我们有一个名为 cricketers_data 的表,其中包含 6 条记录,如下所示

+------------+------------+---------------+----------------+-------------+
| First_Name | Last_Name  | Date_Of_Birth | Place_Of_Birth | Country     |
+------------+------------+---------------+----------------+-------------+
| Shikhar    | Dhawan     | 1981-12-05    | Delhi          | India       |
| Jonathan   | Trott      | 1981-04-22    | CapeTown       | SouthAfrica |
| Lumara     | Sangakkara | 1977-10-27    | Matale         | Srilanka    |
| Virat      | Kohli      | 1987-04-30    | Delhi          | India       |
| Rohit      | Sharma     | 1987-04-30    | Nagpur         | India       |
| Ravindra   | Jamnagar   | 1988-12-06    | NULL           | India       |
+------------+------------+---------------+----------------+-------------+

以下 JDBC 程序建立与数据库的连接,将 cricketers_data 表中的内容检索到一个 ResultSet 对象中,将指针移动到第 3 行,并打印其内容

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ResultSet_DeletingRow {
   public static void main(String args[])throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://127.0.0.1/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating a Statement object
      Statement stmt = con.createStatement();
      //Query to retrieve the contents of the employee_data table
      String query = "select * from cricketers_data";
      //Executing the query
      ResultSet rs = stmt.executeQuery(query);
      //Moving ResultSet object to the required position
      rs.absolute(3);
      //Contents of the current row
      System.out.println("First name: "+rs.getString(1));
      System.out.println("Last name: "+rs.getString(2));
      System.out.println("Date of birth: "+rs.getDate(3));
      System.out.println("Place of birth: "+rs.getString(4));
      System.out.println("Country: "+rs.getString(5));
   }
}

输出

Connection established......
First name: Lumara
Last name: Sangakkara
Date of birth: 1977-10-27
Place of birth: Matale
Country: Srilanka

更新于:2019 年 7 月 30 日

205 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告