如何使用 JDBC 将结果集的指针移动到表尾?
结果集接口的 afterLast() 方法将光标/指针移动到结果集对象的最后一行之后。
rs.afterLast();
假设我们有一张名为 dataset 的表,如下所示
+--------------+-----------+ | mobile_brand | unit_sale | +--------------+-----------+ | Iphone | 3000 | | Samsung | 4000 | | Nokia | 5000 | | Vivo | 1500 | | Oppo | 900 | | MI | 6400 | | MotoG | 4360 | | Lenovo | 4100 | | RedMi | 4000 | | MotoG | 4360 | | OnePlus | 6334 | +--------------+-----------+
下面的示例演示了双向结果集的创建。这里我们尝试创建一个双向结果集对象,从名为 dataset 的表中检索数据,并且我们尝试从最后打印 dataset 表的行到第一行。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class BidirectionalResultSet { 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/TestDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating a Statement object Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); //Retrieving the data ResultSet rs = stmt.executeQuery("select * from Dataset"); rs.afterLast(); System.out.println("Contents of the table"); while(rs.previous()) { System.out.print("Brand: "+rs.getString("Mobile_Brand")+", "); System.out.print("Sale: "+rs.getString("Unit_Sale")); System.out.println(""); } } }
输出
Connection established...... Contents of the table Brand: Vivo, Sale: 1500 Brand: Nokia, Sale: 5000 Brand: Samsung, Sale: 4000 Brand: IPhone, Sale: 3000
广告