Java ResultSet relative() 方法及示例
当我们执行某些SQL查询(通常是SELECT查询)时,它们会返回表格数据。
**java.sql.ResultSet** 接口表示SQL语句返回的此类表格数据。
即 **ResultSet** 对象保存由执行查询数据库的语句(通常是Statement接口的executeQuery()方法)返回的表格数据。
ResultSet对象有一个游标/指针,指向当前行。最初,此游标位于第一行之前。
**ResultSet** 接口的 **relative()** 方法将 ResultSet 指针/游标从当前位置移动 n 行。
此方法返回一个整数值,表示 ResultSet 指针指向的当前行号。
让我们使用如下所示的 CREATE 语句在 MySQL 数据库中创建一个名为 MyPlayers 的表:
CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) );
现在,我们将使用 INSERT 语句在 MyPlayers 表中插入 7 条记录
insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');
下面的 JDBC 程序建立与数据库的连接,将表 MyPlayers 的内容检索到 ResultSet 对象中,检索游标的当前位置,并相对地向前和向后移动它。
示例
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ResultSet_relative { public static void main(String args[]) throws SQLException { //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 the Statement Statement stmt = con.createStatement(); //Query to retrieve records String query = "Select * from MyPlayers"; //Executing the query ResultSet rs = stmt.executeQuery(query); //Moving the cursor to 3rd position rs.absolute(3); System.out.println("Position of the pointer: "+rs.getRow()); //Moving the pointer 2 positions forward from the current System.out.println("Position of the pointer after moving it to 2 places forward relatively: "+rs.relative(2)); //Moving the pointer 3 positions backwards from the current System.out.println("Position of the pointer after moving it to 3 places backward relatively: "+rs.relative(-3)); } }
输出
Connection established...... Position of the pointer: 3 Position of the pointer after moving it to 2 places forward relatively: true Position of the pointer after moving it to 3 places backward relatively: true
广告