如何将结果集指针移动到所需位置?
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对象中,然后将指针移至第三行并打印其内容:
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 { //注册驱动程序 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //获得连接 String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //创建一个Statement对象 Statement stmt = con.createStatement(); //查询以获取employee_data表的内容 String query = "select * from cricketers_data"; //执行查询 ResultSet rs = stmt.executeQuery(query); //将ResultSet对象移动到所需位置 rs.absolute(3); //当前行的内容 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