IDBDatabase: transaction() 方法
注意:此功能在 Web Workers 中可用。
IDBDatabase 介面的 transaction 方法會立即返回一個包含 IDBTransaction.objectStore 方法的事務物件 (IDBTransaction),您可以使用它來訪問您的物件儲存。
語法
js
transaction(storeNames)
transaction(storeNames, mode)
transaction(storeNames, mode, options)
引數
storeNames-
新事務範圍內物件儲存的名稱,宣告為字串陣列。只指定您需要訪問的物件儲存。如果您只需要訪問一個物件儲存,可以將它的名稱指定為字串。因此,以下兩行是等效的
jsdb.transaction(["my-store-name"]); db.transaction("my-store-name");如果您需要訪問資料庫中的所有物件儲存,可以使用
IDBDatabase.objectStoreNames屬性jsconst transaction = db.transaction(db.objectStoreNames);傳入一個空陣列將丟擲異常。
mode可選-
可以在事務中執行的訪問型別。事務以三種模式之一開啟
readonly-
為從物件儲存讀取事務開啟。這是預設模式。
readwrite-
為從物件儲存讀取和寫入事務開啟。只有在需要寫入資料庫時才應使用此模式。
readwriteflush非標準 實驗性-
強制事務在
complete事件發生之前重新整理到磁碟。這可能用於儲存無法稍後重新計算的關鍵資料。
options可選-
定義附加選項的物件,包括
durability-
以下三種字串字面值之一
返回值
IDBTransaction 物件。
異常
InvalidStateErrorDOMException-
如果此
IDBDatabase例項先前已呼叫close()方法,則會丟擲此異常。 NotFoundErrorDOMException-
如果 'storeNames' 引數中指定的物件儲存已被刪除或移除,則會丟擲此異常。
TypeError-
如果
mode引數的值無效,則會丟擲此異常。 InvalidAccessErrorDOMException-
如果函式使用空的物件儲存名稱列表呼叫,則會丟擲此異常。
示例
在此示例中,我們開啟資料庫連線,然後使用 transaction() 在資料庫上開啟一個事務。有關完整示例,請參閱我們的 待辦事項通知 應用(線上檢視示例)。
js
let db;
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onsuccess = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Database initialized.";
// store the result of opening the database in the db variable.
// This is used a lot below
db = DBOpenRequest.result;
// Run the displayData() function to populate the task list with
// all the to-do list data already in the IDB
displayData();
};
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
// report on the success of opening the transaction
transaction.oncomplete = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction completed: database modification finished.";
};
transaction.onerror = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction not opened due to error. Duplicate items not allowed.";
};
// you would then go on to do something to this database
// via an object store
const objectStore = transaction.objectStore("toDoList");
// etc.
規範
| 規範 |
|---|
| Indexed Database API 3.0 # ref-for-dom-idbdatabase-transaction③ |
瀏覽器相容性
載入中…
另見
- 使用 IndexedDB
- 開始事務:
IDBDatabase - 使用事務:
IDBTransaction - 設定鍵的範圍:
IDBKeyRange - 檢索和修改資料:
IDBObjectStore - 使用遊標:
IDBCursor - 參考示例:待辦事項通知(檢視即時示例)。