public class ScrollableResultSetDemo {
public static void main(String[] args) {
String sql = "SELECT * FROM login ORDER BY id";
try (Connection con = DBUtil.getConn();
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, // 可捲動,不敏感於底層變更
ResultSet.CONCUR_UPDATABLE); // 可更新
ResultSet rs = stmt.executeQuery(sql)) {
System.out.println("=== 開始測試游標操作 ===");
// 1. 絕對定位:移到第 2 列
rs.absolute(2);
System.out.println("游標移至第 2 列,當前行號: " + rs.getRow());
// 2. 移到最後一列取得總筆數
rs.last();
System.out.println("總筆數: " + rs.getRow());
// 3. 插入新列
rs.moveToInsertRow();
rs.updateString("username", "newUser");
rs.updateString("password", "123456");
rs.insertRow(); // 寫入資料庫
System.out.println("已插入 1 筆");
rs.moveToInsertRow();
rs.updateString("username", "another");
rs.updateString("password", "abcdef");
rs.insertRow();
System.out.println("再插入 1 筆");
// 4. 驗證總筆數增加
rs.last();
System.out.println("目前總筆數: " + rs.getRow());
// 5. 刪除當前列
rs.deleteRow();
rs.last();
System.out.println("刪除後總筆數: " + rs.getRow());
System.out.println("=== 測試完成 ===");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| 常數 | 說明 |
|---|---|
TYPE_FORWARD_ONLY | 預設,僅能向前移動,不可捲動 |
TYPE_SCROLL_INSENSITIVE | 可捲動,結果集為快照,不反映他人提交的變更 |
TYPE_SCROLL_SENSITIVE | 可捲動,即時反映他人提交的變更(效能較差) |
CONCUR_READ_ONLY | 預設,唯讀 |
CONCUR_UPDATABLE | 可更新:支援 updateXxx、insertRow、deleteRow、refreshRow |
absolute(int row):移至指定行號(1-based)。relative(int rows):相對當前位置移動(正向前、負向後)。first()、last()、beforeFirst()、afterLast()。next()、previous()。getRow():取得當前行號(0 表示游標在 beforeFirst/afterLast)。moveToInsertRow() → 切換至插入緩衝區。updateXxx(column, value) → 設定各欄位新值。insertRow() → 寫入資料庫並移回原游標位置。updateXxx → updateRow()。deleteRow()。TYPE_SCROLL_INSENSITIVE 較通用,SENSITIVE 驅動支援度較低。LIMIT/OFFSET 或 FETCH),避免一次載入所有記憶體。con.setAutoCommit(false)。可捲動/可更新 ResultSet 讓 Java 程式能像操作記憶體集合一樣操作資料庫結果集,極大簡化 CRUD 邏輯。掌握游標移動與更新流程,並注意主鍵與交易邊界,即可在適當場景(如桌面應用、批次工具)高效運用。