IDBFactory: open() 方法
注意:此功能在 Web Workers 中可用。
open() 方法是 IDBFactory 介面的一個方法,用於請求開啟一個資料庫連線。
該方法會立即返回一個 IDBOpenDBRequest 物件,並非同步執行開啟操作。如果操作成功,將會在該方法返回的請求物件上觸發一個 success 事件,其 result 屬性將被設定為新資料庫連線的 IDBDatabase 物件。
可能會觸發 upgradeneeded、blocked 或 versionchange 事件。
語法
js
open(name)
open(name, version)
引數
name-
資料庫的名稱。
version可選-
可選。用於開啟資料庫的版本號。如果未提供版本號且資料庫已存在,則會以不更改其版本的方式開啟資料庫連線。如果未提供版本號且資料庫不存在,則會以版本號
1建立資料庫。
返回值
一個 IDBOpenDBRequest 物件,後續與此請求相關的事件將在此物件上觸發。
如果操作成功,請求的 result 屬性的值將是一個代表資料庫連線的 IDBDatabase 物件。
異常
TypeError-
如果
version的值不是大於零的數字,則會丟擲此異常。
示例
呼叫 open 並使用當前規範的 version 引數的示例
js
const request = window.indexedDB.open("toDoList", 4);
在下面的程式碼片段中,我們發出請求開啟一個數據庫,幷包含成功和錯誤情況的處理程式。有關完整的可工作示例,請參閱我們的 待辦事項通知 應用(即時檢視示例)。
js
const note = document.querySelector("ul");
// Let us open version 4 of our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
// these two event handlers act on the database being opened
// successfully, or not
DBOpenRequest.onerror = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Error loading database.";
};
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 later on, for opening
// transactions and suchlike.
db = DBOpenRequest.result;
};
規範
| 規範 |
|---|
| Indexed Database API 3.0 # ref-for-dom-idbfactory-open② |
瀏覽器相容性
載入中…
另見
- 使用 IndexedDB
- 瀏覽器儲存配額和淘汰標準.
- 開始事務:
IDBDatabase - 使用事務:
IDBTransaction - 設定鍵的範圍:
IDBKeyRange - 檢索和修改資料:
IDBObjectStore - 使用遊標:
IDBCursor - 參考示例:待辦事項通知(檢視即時示例)。