IDBFactory.open
IDBFactory.open
方法用于打开一个数据库连接。本方法立即返回一个 IDBOpenDBRequest
对象,但打开数据库的操作是异步执行的。
连接数据库在一个单独的线程中进行,包括以下几个步骤:
-
指定数据库已经存在时:
- 等待
versionchange
操作完成。 - 如果数据库已计划删除,那等着删除完成。
- 等待
-
如果已有数据库版本高于给定的
version
,中止操作并返回类型为VersionError
的DOMError
。 -
如果已有数据库版本低于给定的
version
,触发一个versionchange
操作。 -
如果数据库不存在,创建指定名称的数据库,将版本号设置为给定版本,如果给定版本号,则设置为 1,and no object stores.
-
创建数据库连接。
如果操作成功执行,将触发 success
事件 on the request object that is returned from this method, with its result
attribute set to the new IDBDatabase
object for the connection.
If an error occurs while the database connection is being opened, then an error event is fired on the request object returned from this method.
语法
open(name)
open(name, version)
参数
- name
-
数据库名称
- version
-
指定数据库版本,当你想要更改数据库格式(比如增加对象存储,非增加记录),必须指定更高版本,通过 versionchange 来更改
- options (version and storage) 非标准
-
In Gecko, since version 26, you can include an
options
object as a parameter ofIDBFactory.open
that contains theversion
number of the database, plus a storage value that specifies whether you want to usepermanent
(the default value) storage for the IndexedDB, ortemporary
storage (aka shared pool.) See Firefox bug 785884 for more details. This is a non-standard feature that we are looking to standardise sometime in the future.
备注:Data in temporary storage persists until the global limit for the pool is reached. The global limit calculation is relatively complex, but we are considering changing it (see Firefox bug 968272). When the global limit is reached, then data for the least recently used origin is deleted. There's also a group limit (eTLD+1 group/domain) which is currently 20% of the global limit. All requets that would exceed the group limit are just rejected.
返回
IDBOpenDBRequest
-
The request object on which subsequent events related to this request are fired.
Exceptions
This method may raise a DOMException
with a DOMError of the following types:
Exception | 描述 |
---|---|
TypeError |
The value of version is zero or a negative number or not a number. |
示例
使用当前规范的 version
参数调用 open
的示例:
const request = window.indexedDB.open("toDoList", 4);
带有 options
的实验性版本(见下文):
const note = document.querySelector("ul");
// 打开数据库的第四个版本
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
// 这两个事件处理器处理数据库成功打开或失败的情况
DBOpenRequest.onerror = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Error loading database.";
};
DBOpenRequest.onsuccess = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Database 已初始化。";
// 将打开数据库的结果存储到 db 变量中。
// 这在后面的打开事务等操作中经常使用。
db = DBOpenRequest.result;
};
规范
Specification |
---|
Indexed Database API 3.0 # ref-for-dom-idbfactory-open② |
浏览器兼容性
BCD tables only load in the browser