如何使用 JDBC 找到 ResultSet 对象的当前行?
getRow() 方法 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 对象,并打印 ResultSet 指针的当前位置。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class ResultSet_CurrentRow { 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 the ResultSet pointer to a particular position rs.absolute(2); //Getting the current row of the ResultSet object int current_row = rs.getRow(); System.out.println(current_row); } }
输出
Connection established...... 2
广告