首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> J2EE

分散式資料庫客戶端資料集選型:Vector vs RowSet (CachedRowSet) 實戰比較

     編輯:J2EE

方案一:Vector 傳回主鍵集合


public Enumeration ejbFindBigAccounts(double balanceGreaterThan) {
    // ... JDBC 查詢 ...
    Vector v = new Vector();
    while (rs.next()) {
        v.addElement(rs.getString(1)); // 主鍵
    }
    return v.elements();
}

缺點:僅傳回主鍵,客戶端需再查詢明細;非標準集合介面,使用不便。

方案二:RowSet (CachedRowSet) - 推薦

RowSet 為介面,Sun 規範提供三種實作:CachedRowSet、JdbcRowSet、WebRowSet。JDK 1.4 未內建實作類,需下載 jdbc2.0-optional-package (rowset.jar)。

安裝步驟

  1. 解壓取得 rowset.jar 放置任意目錄(如 d:\jdk1.4\jre\rowset.jar)
  2. IDE 增加庫路徑 ROWSET_PATH 指向該 jar
  3. 專案屬性加入該路徑
  4. 原始碼 import sun.jdbc.rowset.*;

伺服器端範例:回傳 CachedRowSet


// CoffeesBean.java
public RowSet getCoffees() throws SQLException {
    Connection con = ds.getConnection("webCustomer", "webPassword");
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("select * from coffees");
    CachedRowSet crs = new CachedRowSet();
    crs.populate(rs); // 斷線快取
    crs.setTableName("coffees"); // 供更新用
    rs.close(); stmt.close(); con.close();
    return crs;
}

public void updateCoffees(RowSet rs) throws SQLException {
    CachedRowSet crs = (CachedRowSet) rs;
    Connection con = ds.getConnection("webCustomer", "webPassword");
    crs.acceptChanges(con); // 將快取變更寫回資料庫
    con.close();
}

客戶端範例:離線修改後送回更新


// CoffeesClient.java
CachedRowSet rset = (CachedRowSet) coffees.getCoffees();
while (rset.next()) {
    if ("Columbian".equalsIgnoreCase(rset.getString("COF_NAME"))) {
        rset.updateFloat("PRICE", rset.getFloat("PRICE") * 1.10f);
        rset.updateRow();
    }
}
coffees.updateCoffees(rset); // 送回伺服器寫入

CachedRowSet 核心優勢

  • 斷線快取:資料在記憶體中可離線操作,類似 ADO Recordset
  • 可序列化:適合遠端傳輸 (RMI/HTTP)
  • 支援更新:acceptChanges() 自動產生 SQL 寫回
  • 游標操作:next(), previous(), absolute() 等豐富導航

結論

CachedRowSet 是分散式環境下傳遞表格資料的最佳選擇,解決 Vector 只能傳主鍵的缺陷,提供豐富的離線操作與更新能力。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved