IDBObjectStore: put() 方法
注意:此功能在 Web Workers 中可用。
put() 方法是 IDBObjectStore 介面的一個方法,用於更新資料庫中指定記錄,或者在指定的項不存在時插入一條新記錄。
它會返回一個 IDBRequest 物件,並在單獨的執行緒中建立一個結構化克隆(structured clone)的 value,然後將其儲存到物件儲存中。這用於在事務模式為 readwrite 時新增新記錄或更新現有記錄。如果記錄儲存成功,則在返回的請求物件上會觸發一個 success 事件,其 result 屬性設定為儲存記錄的鍵,transaction 屬性設定為開啟此物件儲存的事務。
put 方法是更新或插入方法。有關僅插入的方法,請參閱 IDBObjectStore.add 方法。
請注意,如果您要更新的記錄擁有一個 IDBCursor,那麼使用 IDBCursor.update() 來更新它比使用 IDBObjectStore.put() 更可取。這樣做可以清楚地表明要更新的是現有記錄,而不是插入新記錄。
語法
put(item)
put(item, key)
引數
item-
您希望更新(或插入)的項。
key可選-
您想更新的記錄的主鍵(例如,來自
IDBCursor.primaryKey)。
返回值
一個 IDBRequest 物件,後續與此操作相關的事件會在此物件上觸發。
如果操作成功,請求的 result 屬性的值將是新記錄或更新記錄的鍵。
異常
此方法可能會丟擲以下型別之一的DOMException:
ReadOnlyErrorDOMException-
如果與此操作關聯的事務處於只讀 模式,則會丟擲此異常。
TransactionInactiveErrorDOMException-
如果此
IDBObjectStore的事務不活躍,則會丟擲此異常。 DataErrorDOMException-
如果滿足以下任一條件,則會丟擲此異常:
InvalidStateErrorDOMException-
如果
IDBObjectStore已被刪除或移除,則會丟擲此異常。 DataCloneErrorDOMException-
如果正在儲存的資料無法透過內部結構化克隆演算法進行克隆,則會丟擲此異常。
示例
以下示例請求一個給定的記錄標題;當該請求成功時,onsuccess 函式會從 IDBObjectStore(透過 objectStoreTitleRequest.result 可獲得)獲取關聯的記錄,更新記錄的一個屬性,然後使用 put() 方法將更新後的記錄放回物件儲存。有關完整的可工作示例,請參閱我們的 To-do Notifications 應用(線上檢視示例)。
const title = "Walk dog";
// Open up a transaction as usual
const objectStore = db
.transaction(["toDoList"], "readwrite")
.objectStore("toDoList");
// Get the to-do list object that has this title as its title
const objectStoreTitleRequest = objectStore.get(title);
objectStoreTitleRequest.onsuccess = () => {
// Grab the data object returned as the result
const data = objectStoreTitleRequest.result;
// Update the notified value in the object to "yes"
data.notified = "yes";
// Create another request that inserts the item back into the database
const updateTitleRequest = objectStore.put(data);
// Log the transaction that originated this request
console.log(
`The transaction that originated this request is ${updateTitleRequest.transaction}`,
);
// When this new request succeeds, run the displayData() function again to update the display
updateTitleRequest.onsuccess = () => {
displayData();
};
};
規範
| 規範 |
|---|
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-put① |
瀏覽器相容性
載入中…
另見
- 使用 IndexedDB
- 開始事務:
IDBDatabase - 使用事務:
IDBTransaction - 設定鍵的範圍:
IDBKeyRange - 檢索和修改資料:
IDBObjectStore - 使用遊標:
IDBCursor - 參考示例:待辦事項通知(檢視即時示例)。