如何使用 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:///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

更新於:2019 年 7 月 30 日

93 次瀏覽

開啟您的 職業

完成課程認證

立即開始
廣告
© . All rights reserved.