RowSet 是否可滾動?透過一個示例說明?


RowSet 物件類似於 ResultSet,它也儲存表格資料,除了 ResultSet 的特性。RowSet 遵循 JavaBeans 元件模型。

如果你透過預設方式檢索一個 ResultSet 物件,它的游標只能向前移動。也就是說,你可以從頭到尾檢索它的內容。

但是,在一個可滾動的結果集中,游標可以向前和向後滾動,你也可以向後檢索資料。

要使 ResultSet 物件可滾動,你需要像下面這樣建立一個物件 -

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

而 RowSet 物件預設情況下是可滾動的。因此,每當底層資料庫不提供可滾動 ResultSet 物件時,你可以使用 RowSet。

示例

假設我們在資料庫中有一個名為 Dispatches 的表,其中有 5 條記錄,如下所示 -

+-------------+--------------+--------------+--------------+-------+----------------+
| ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location       |
+-------------+--------------+--------------+--------------+-------+----------------+ 
| Key-Board   | Raja         | 2019-09-01   | 05:30:00     | 7000  | Hyderabad      |
| Earphones   | Roja         | 2019-05-01   | 05:30:00     | 2000  | Vishakhapatnam |
| Mouse       | Puja         | 2019-03-01   | 05:29:59     | 3000  | Vijayawada     |
| Mobile      | Vanaja       | 2019-03-01   | 04:40:52     | 9000  | Chennai        |
| Headset     | Jalaja       | 2019-04-06   | 18:38:59     | 6000  | Goa            |
+-------------+--------------+--------------+--------------+-------+----------------+

以下 JDBC 程式將從後到前檢索 RowSet 的內容

import java.sql.DriverManager;
import javax.sql.RowSet;
import javax.sql.rowset.RowSetProvider;
public class ScrolableUpdatableRowSet {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Creating the RowSet object
      RowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
      //Setting the URL
      String mysqlUrl = "jdbc:mysql:///SampleDB";
      rowSet.setUrl(mysqlUrl);
      //Setting the user name
      rowSet.setUsername("root");
      //Setting the password
      rowSet.setPassword("password");
      //Setting the query/command
      rowSet.setCommand("select * from Dispatches");
      rowSet.setCommand("SELECT ProductName, CustomerName, Price, Location from Dispatches where price > ?");
      rowSet.setInt(1, 2000);
      rowSet.execute();
      rowSet.afterLast();
      while(rowSet.previous()) {
         System.out.print("Product Name: "+rowSet.getString("ProductName")+", ");
         System.out.print("Customer Name: "+rowSet.getString("CustomerName")+", ");
         System.out.print("Price: "+rowSet.getString("Price")+", ");
         System.out.print("Location: "+rowSet.getString("Location"));
         System.out.println("");
      }
   }
}

輸出

Product Name: Headset, Customer Name: Jalaja, Price: 6000, Location: Vijayawada
Product Name: Mobile, Customer Name: Vanaja, Price: 9000, Location: Vijayawada
Product Name: Mouse, Customer Name: Puja, Price: 3000, Location: Vijayawada
Product Name: Key-Board, Customer Name: Raja, Price: 7000, Location: Hyderabad

更新於: 2019 年 7 月 30 日

393 個瀏覽量

開啟你的 事業

完成課程以獲得認證

開始
廣告