public Enumeration ejbFindBigAccounts(double balanceGreaterThan) {
// ... JDBC 查詢 ...
Vector v = new Vector();
while (rs.next()) {
v.addElement(rs.getString(1)); // 主鍵
}
return v.elements();
}
缺點:僅傳回主鍵,客戶端需再查詢明細;非標準集合介面,使用不便。
RowSet 為介面,Sun 規範提供三種實作:CachedRowSet、JdbcRowSet、WebRowSet。JDK 1.4 未內建實作類,需下載 jdbc2.0-optional-package (rowset.jar)。
rowset.jar 放置任意目錄(如 d:\jdk1.4\jre\rowset.jar)ROWSET_PATH 指向該 jarimport sun.jdbc.rowset.*;
// 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); // 送回伺服器寫入
acceptChanges() 自動產生 SQL 寫回next(), previous(), absolute() 等豐富導航CachedRowSet 是分散式環境下傳遞表格資料的最佳選擇,解決 Vector 只能傳主鍵的缺陷,提供豐富的離線操作與更新能力。