From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/api/idbobjectstore/add/index.html | 179 +++++ .../api/idbobjectstore/autoincrement/index.html | 133 ++++ files/zh-cn/web/api/idbobjectstore/get/index.html | 149 ++++ files/zh-cn/web/api/idbobjectstore/index.html | 759 +++++++++++++++++++++ .../web/api/idbobjectstore/indexnames/index.html | 110 +++ .../web/api/idbobjectstore/keypath/index.html | 115 ++++ .../web/api/idbobjectstore/opencursor/index.html | 171 +++++ files/zh-cn/web/api/idbobjectstore/put/index.html | 163 +++++ 8 files changed, 1779 insertions(+) create mode 100644 files/zh-cn/web/api/idbobjectstore/add/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/autoincrement/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/get/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/indexnames/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/keypath/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/opencursor/index.html create mode 100644 files/zh-cn/web/api/idbobjectstore/put/index.html (limited to 'files/zh-cn/web/api/idbobjectstore') diff --git a/files/zh-cn/web/api/idbobjectstore/add/index.html b/files/zh-cn/web/api/idbobjectstore/add/index.html new file mode 100644 index 0000000000..b953262c13 --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/add/index.html @@ -0,0 +1,179 @@ +--- +title: IDBObjectStore.add() +slug: Web/API/IDBObjectStore/add +translation_of: Web/API/IDBObjectStore/add +--- +

{{ APIRef("IndexedDB") }}

+ +
+

{{domxref("IDBObjectStore")}} 接口中的 add() 方法返回一个 {{domxref("IDBRequest")}} 对象,在单独的线程中创建一个结构(structured clone)化克隆值,并且在对象存储中存储这个克隆值。这个方法用作在一个对象存储中添加一条新的记录。

+
+ +

 要确定添加操作是否成功完成,可以监听事务的 complete 事件。除了 IDBObjectStore.add 请求 success 事件之外,因为事务在成功被触发后仍然可能失败。换句话说,成功事件只有在事务成功排队后才会触发。

+ +

add() 方法是唯一的插入方法。如果以关键字参数作为主键的一条记录已经存在在存储对象中,这时在返回的请求对象中 ConstrainError 错误事件将被触发。对于更新存在的记录,你应该使用 {{domxref("IDBObjectStore.put")}} 方法替代它。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var request = objectStore.add(value);
+var request = objectStore.add(value, key);
+
+ +

参数

+ +
+
value
+
需要存储的值。
+
key {{optional_inline}}
+
关键字用于识别记录。如果未指明,即为空。
+
+ +

返回

+ +

一个 {{domxref("IDBRequest")}} 对象,在该操作对象中触发与此相关的后续事件。

+ +

异常

+ +

这个方法可能导致以下类型中的一个 {{domxref("DOMException")}} :

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
ReadOnlyError与此操作相关联的事务处于只读模式。
TransactionInactiveError当前 {{domxref("IDBObjectStore")}} 事务不可用。
DataError +

适用于以下任何条件:

+ +
    +
  • 对象存储使用内联键或者拥有密钥生成器(键生成器),并且提供了键参数。
  • +
  • 对象存储使用外联键或者没有密钥生成器(键生成器),并且没有提供键参数。
  • +
  • 对象存储使用内联键但是没有密钥生成器(键生成器),并且对象存储的键路径不会产生一个有效的键值。
  • +
  • 键参数已经被提供,但是不包含一个有效的键。
  • +
+
InvalidStateError +

{{domxref("IDBObjectStore")}} 已经被删除或者移除。

+
DataCloneError通过内部结构的克隆算法,被存储的数据无法被克隆
+  
ConstraintError +

因为主键违法规定导致的插入操作失败(由于已存在的记录使用了相同的主键值)。

+
+ +

示例

+ +

在以下的代码片段中,在我们数据库中打开一个 read/write(读写)事务和使用 add() 方法添加一些数据到存储对象中。还要注意附加到事务事件处理程序的函数,这些函数用于报告事务打开成功或失败时的结果。完整的示例代码,请查看我们的 To-do Notifications 应用 在线查看示例 )。

+ +
// Let us open our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+DBOpenRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Database initialised.</li>';
+
+  // store the result of opening the database in the db variable.
+  // This is used a lot below
+  db = DBOpenRequest.result;
+
+  // Run the addData() function to add the data to the database
+  addData();
+};
+
+function addData() {
+  // Create a new object ready to insert into the IDB
+  var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ];
+
+  // open a read/write db transaction, ready for adding the data
+  var transaction = db.transaction(["toDoList"], "readwrite");
+
+  // report on the success of the transaction completing, when everything is done
+  transaction.oncomplete = function(event) {
+    note.innerHTML += '<li>Transaction completed.</li>';
+  };
+
+  transaction.onerror = function(event) {
+  note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+  };
+
+  // create an object store on the transaction
+  var objectStore = transaction.objectStore("toDoList");
+
+  // Make a request to add our newItem object to the object store
+  var objectStoreRequest = objectStore.add(newItem[0]);
+
+  objectStoreRequest.onsuccess = function(event) {
+    // report the success of our request
+    note.innerHTML += '<li>Request successful.</li>';
+  };
+};
+ +

Specification

+ +
+
+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#dom-idbobjectstore-add', 'add()')}}{{Spec2('IndexedDB')}}
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-add", "add()")}}{{Spec2("IndexedDB 2")}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.IDBObjectStore.add")}}

+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/idbobjectstore/autoincrement/index.html b/files/zh-cn/web/api/idbobjectstore/autoincrement/index.html new file mode 100644 index 0000000000..0a4aca4377 --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/autoincrement/index.html @@ -0,0 +1,133 @@ +--- +title: IDBObjectStore.autoIncrement +slug: Web/API/IDBObjectStore/autoIncrement +translation_of: Web/API/IDBObjectStore/autoIncrement +--- +

{{ APIRef("IndexedDB") }}

+ +
+

{{domxref("IDBObjectStore")}}的只读属性autoIncrement接口返回当前objectStore的自增标记值(true或false)。

+ +

什么是自增呢?熟悉SQL的朋友应该知道,SQL数据里面的字段可以设置自增,当一条记录被插入时,不必传入该字段,新记录的该字段值会在前面一条记录该字段值的基础上加1.而indexedDB里面的autoIncrement的同样的意义。(译者注)

+ +

注意:每个objectStore的auto increment计数器是分开独立的。

+ +

{{AvailableInWorkers}}

+
+ +

句法

+ +
var myAutoIncrement = objectStore.autoIncrement;
+ +

Value

+ +

{{domxref("Boolean")}}:

+ + + + + + + + + + + + + + + + + + +
含义
true当前objectStore会自增
false当前objectStore不会自增
+  
+ +

例子

+ +

在下面代码片段中,我们在数据库里打开了一个可读写的事务(transaction),并且用add()向一个objectStore中添加了一些数据。在objectStore被创建之后,我们在console中打印了objectStore.autoIncrement的值。想查看完整的例子,请查看我们的To-do Notifications应用(查看在线例子)。

+ +
// Let us open our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+DBOpenRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Database initialised.</li>';
+
+  // store the result of opening the database in the db variable.
+  // This is used a lot below
+  db = DBOpenRequest.result;
+
+  // Run the addData() function to add the data to the database
+  addData();
+};
+
+function addData() {
+  // Create a new object ready to insert into the IDB
+  var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ];
+
+  // open a read/write db transaction, ready for adding the data
+  var transaction = db.transaction(["toDoList"], "readwrite");
+
+  // report on the success of the transaction completing, when everything is done
+  transaction.oncomplete = function(event) {
+    note.innerHTML += '<li>Transaction completed.</li>';
+  };
+
+  transaction.onerror = function(event) {
+    note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+  };
+
+  // create an object store on the transaction
+  var objectStore = transaction.objectStore("toDoList");
+  console.log(objectStore.autoIncrement);
+
+  // Make a request to add our newItem object to the object store
+  var objectStoreRequest = objectStore.add(newItem[0]);
+
+  objectStoreRequest.onsuccess = function(event) {
+    // report the success of our request
+    note.innerHTML += '<li>Request successful.</li>';
+  };
+};
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('IndexedDB', '#widl-IDBObjectStore-autoIncrement', 'autoIncrement')}}{{Spec2('IndexedDB')}} 
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-autoincrement", "autoIncrement")}}{{Spec2("IndexedDB 2")}} 
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.IDBObjectStore.autoIncrement")}}

+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/idbobjectstore/get/index.html b/files/zh-cn/web/api/idbobjectstore/get/index.html new file mode 100644 index 0000000000..fb7938d827 --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/get/index.html @@ -0,0 +1,149 @@ +--- +title: IDBObjectStore.get() +slug: Web/API/IDBObjectStore/get +translation_of: Web/API/IDBObjectStore/get +--- +

{{ APIRef("IndexedDB") }}

+ +
+

{{domxref("IDBObjectStore")}} 的接口 get()方法 返回 {{domxref("IDBRequest")}} 对象,并在“单独的线程(separate thread)”中返回由指定键选择的“对象储存(object store)” 。这用于从对象储存检索特定记录。

+
+ +

如果成功找到值,则会创建其值的结构化克隆,并设置为“请求对象(request object)”的 result

+ +

{{ Note("This method produces the same result for: a) a record that doesn't exist in the database and b) a record that has an undefined value. To tell these situations apart, call the openCursor() method with the same key. That method provides a cursor if the record exists, and no cursor if it does not.") }}

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var request = objectStore.get(key);
+ +

参数

+ +
+
key
+
标识要检索的记录的键或键范围
+
+ +

返回值

+ +

触发与此操作相关的后续事件的 {{domxref("IDBRequest")}} 对象。

+ +

异常

+ +

此方法可能会引发以下类型之一的 {{domxref("DOMException")}} :

+ + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
TransactionInactiveErrorThis {{domxref("IDBObjectStore")}}'s transaction is inactive.
DataError +

The key or key range provided contains an invalid key.

+
InvalidStateErrorThe {{domxref("IDBObjectStore")}} has been deleted or removed.
+  
+ +

例子

+ +

在以下的代码段中,我们在数据库上打开一个“读/写 事务(read/write transaction)”,并使用 get() 从“对象储存( object store )”中获取一个特定的记录——一个带有“Walk dog”键的示例记录。一旦检索到这个数据对象,你就可以使用普通的JavaScript更新它,然后使用 {{domxref("IDBObjectStore.put")}} 操作将其放回数据库。有关完整的工作示例,查看我们的 To-do Notifications app (view example live.)

+ +
// Let us open our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+DBOpenRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Database initialised.</li>';
+
+  // store the result of opening the database in the db variable.
+  // This is used a lot below
+  db = DBOpenRequest.result;
+
+  // Run the getData() function to get the data from the database
+  getData();
+};
+
+function getData() {
+  // open a read/write db transaction, ready for retrieving the data
+  var transaction = db.transaction(["toDoList"], "readwrite");
+
+  // report on the success of the transaction completing, when everything is done
+  transaction.oncomplete = function(event) {
+    note.innerHTML += '<li>Transaction completed.</li>';
+  };
+
+  transaction.onerror = function(event) {
+    note.innerHTML += '<li>Transaction not opened due to error: ' + transaction.error + '</li>';
+  };
+
+  // create an object store on the transaction
+  var objectStore = transaction.objectStore("toDoList");
+
+  // Make a request to get a record by key from the object store
+  var objectStoreRequest = objectStore.get("Walk dog");
+
+  objectStoreRequest.onsuccess = function(event) {
+    // report the success of our request
+    note.innerHTML += '<li>Request successful.</li>';
+
+    var myRecord = objectStoreRequest.result;
+  };
+
+};
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#dom-idbobjectstore-get', 'get()')}}{{Spec2('IndexedDB')}}
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-get", "get()")}}{{Spec2("IndexedDB 2")}}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.IDBObjectStore.get")}}

+
+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/idbobjectstore/index.html b/files/zh-cn/web/api/idbobjectstore/index.html new file mode 100644 index 0000000000..172820799e --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/index.html @@ -0,0 +1,759 @@ +--- +title: IDBObjectStore +slug: Web/API/IDBObjectStore +tags: + - API + - IDBObjectStore + - IndexedDB + - Storage + - local storage & cache +translation_of: Web/API/IDBObjectStore +--- +

{{APIRef("IndexedDB")}}

+ +

 IndexedDB API  的 IDBObjectStore 接口表示数据库中的 一个 对象库(object store) 。对象库中的记录根据其键值进行排序。这种排序可以实现快速插入,查找和有序检索。

+ +

{{AvailableInWorkers}}

+ +

注:为了方便理解,可以把“对象存储空间”想象成关系数据库的“表”结构,下文也会把对象存储空间称为表。

+ +

方法预览

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
IDBRequest add (in any value, in optional any key) raises (DOMException);
IDBRequest clear () raises (DOMException);
IDBRequest count (in optional any key) raises(DOMException);
IDBIndex createIndex  (in DOMString name, in DOMString keyPath, in optional boolean unique) raises (DOMException);
IDBRequest delete (in any key) raises (DOMException);
void deleteIndex (in any DOMString indexName) raises (DOMException);
IDBRequest get (in any key) raises (DOMException);
IDBIndex index (in DOMString name) raises (DOMException);
IDBRequest openCursor (in optional IDBKeyRange range, in optional unsigned short direction) raises(DOMException);
IDBRequest put (in any value, in optional any key) raises (DOMException);
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeTypeDescription
indexNamesreadonly DOMStringList表中对象的索引名列表。
keyPathreadonly DOMString表中的键路径,如果该属性为null,每次操作表时必须提供一个键名。
namereadonly DOMString表名
transactionreadonly IDBTransaction事务的名称,该表属于此事务。
autoIncrementreadonly boolean表中自增字段的值
+ +

方法

+ +

add()

+ +

返回一个IDBRequest对象,并且在新线程中克隆一个值,该值存储在表中。

+ +

想知道是否成功添加数据,可以在事务的complete事件中进行监听,而不是success,因为事务在success事件之后还有可能失败。

+ +

add方法只能插入数据。如果以key参数作为某记录的关键字,并且该条记录已存在,则其所返回的请求对象会产生ConstrainError错误。

+ +
IDBRequest add (in any value, in optional any key) raises (DOMException);
+ +
参数
+ +
+
value
+
被存储的值。
+
key
+
标识某条记录的键,如果不指定,它会被设为null。
+
+ +
返回
+ +
+
IDBRequest
+
一个请求对象,可以在其中绑定事件。
+
+ +
异常
+ +

该方法会抛出DOMError类型的DOMException异常。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
ReadOnlyErrorThe transaction associated with this operation is in read-only mode.
TransactionInactiveErrorThis IDBObjectStore's transaction is inactive.
DataError +

Any of the following conditions apply:

+ +
    +
  • The object store uses in-line keys or has a key generator, and a key parameter was provided.
  • +
  • The object store uses out-of-line keys and has no key generator, and no key parameter was provided.
  • +
  • The object store uses in-line keys but no key generator, and the object store's key path does not yield a valid key.
  • +
  • The key parameter was provided but does not contain a valid key.
  • +
+
InvalidStateErrorThe IDBObjectStore has been deleted or removed.
DataCloneErrorThe data being stored could not be cloned by the internal structured cloning algorithm.
+ +

clear()

+ +

创建并立即返回一个 IDBRequest 对象, 并且在一个单独的线程中清除这个对象存储. 清除对象存储包括从对象存储中删除所有的记录,并删除对象存储引用的索引中的所有记录。

+ +
IDBRequest clear () raises (DOMException);
+ +
Returns
+ +
+
IDBRequest
+
返回一个request对象,在其上触发与操作相关的事件。
+
+ +
Exceptions
+ +

此方法可能会引发domException,其中domError的类型如下:

+ + + + + + + + + + + + + + + + + + +
ExceptionDescription
ReadOnlyErrorThe transaction associated with this operation is in read-only mode.
TransactionInactiveErrorThis IDBObjectStore's transaction is inactive.
+ +

count()

+ +

立即返回一个 IDBRequest 对象,并在新线程中计算符合条件的对象的数量,该方法的参数可以是键,或键范围(key range)。在 IDBRequest 对象中,source属性就是IDBObjectStore对象,result属性持有计算后的数量值。如果参数非法将会抛出异常。

+ +
IDBRequest count (in optional any key) raises(DOMException);
+ +
参数
+ +
+
key
+
计算被该键或键范围(key range)所标识的记录数。
+
+ +
Returns
+ +
+
IDBRequest
+
一个请求对象,可绑定事件。
+
+ +
异常
+ +

该方法会引发如下异常:

+ + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
TransactionInactiveError事务已闲置
DataError +

key参数非法

+
InvalidStateErrorIDBObjectStore对象已被删除
+ +

createIndex()

+ +
+
+ +

创建并返回新的IDBIndex对象,该方法只能从versionchange事务模式的回调方法中被调用。

+ +
IDBIndex createIndex  (in DOMString name, in DOMString keyPath, in optional boolean unique) raises (DOMException);
+ +
Parameters
+ +
+
name
+
The name of the index to create.
+
keyPath
+
The key path for the index to use.
+
optionalParameters
+
+

The IDBIndexParameters object whose attributes are optional parameters to the method. It includes the following properties:

+ + + + + + + + + + + + + + + + + + +
AttributeDescription
uniqueIf true, the index will not allow duplicate values for a single key.
multiEntryIf true, the index will add an entry in the index for each array element when the keypath resolves to an Array. If false, it will add one single entry containing the Array.
+
+
+ +
Returns
+ +
+
IDBIndex
+
The newly created index.
+
+ +
Exceptions
+ +

This method may raise a DOMException with a DOMError of the following types:

+ + + + + + + + + + + + + + + + + + +
ExceptionDescription
InvalidStateErrorThe IDBObjectStore has been deleted or removed or the method was not called from a versionchange transaction mode callback.
ConstraintErrorAn index with the same name (case-sensitive) already exists in the database.
+  
+ +

delete()

+ +
+
+ +

Immediately returns an IDBRequest object, and removes the records specified by the given key or key range from this object store, and any indexes that reference it, in a separate thread.

+ +
IDBRequest delete (in any key) raises (DOMException);
+ +
Parameters
+ +
+
key
+
The key or key range that identifies the records.
+
+ +
Returns
+ +
+
IDBRequest
+
A request object on which subsequent events related to this operation are fired. As per spec the result of the Object Store Deletion Operation algorithm is undefined, so it's not possible to know if some records were actually deleted by looking at the request result.
+
+ +
Exceptions
+ +

This method may raise a DOMException with a DOMError of the following types:

+ + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
TransactionInactiveErrorThis IDBObjectStore's transaction is inactive.
ReadOnlyError +

The transaction associated with this operation is in read-only mode.

+
DataErrorThe key or key range provided contains an invalid key.
+ +
+
+ +
+

If the key that identifies the record is a Number, the key passed to the delete method must be a Number too, and not a String. So for example you might need to do the following:

+ +
var key_val = '42';
+var key = Number(key_val);
+objectstore.delete(key);
+
+ +

deleteIndex()

+ +

Destroys the index with the specified name in the connected database. Note that this method must be called only from a VersionChange transaction mode callback. Note that this method synchronously modifies the indexNames property.

+ +
void deleteIndex (in any DOMString indexName) raises (DOMException);
+ +
Parameters
+ +
+
indexName
+
The name of the existing index to remove.
+
Returns
+
Void
+
+ +
Exceptions
+ +

This method may raise a DOMException with a DOMError of the following types:

+ + + + + + + + + + + + + + + + + + +
ExceptionDescription
InvalidStateErrorThe method was not called from a versionchange transaction mode callback.
NotFoundErrorThere is no index with the given name (case-sensitive) in the database.
+ +

get()

+ +

Immediately returns an IDBRequest object, and retrieves the requested record from the object store in a separate thread. If the operation is successful, then a success event is fired on the returned object, with its result set to the retrieved value, and transaction set to the transaction in which this object store is opened. 

+ +
IDBRequest get (in any key) raises (DOMException);
+ +

{{ Note("This function produces the same result if no record with the given key exists in the database as when a record exists, but with an undefined value. To tell these situations apart, call the openCursor() method with the same key. That method provides a cursor if the record exists, and no cursor if it does not.") }}

+ +
Parameters
+ +
+
key
+
The key or key range identifying the record to retrieve. In the case of a key range, the record returned is the first record associated with the first key in the range.
+
+ +
Returns
+ +
+
IDBRequest
+
A request object on which subsequent events related to this operation are fired.
+
+ +
Exceptions
+ +

This method may raise a DOMException with a DOMError of the following types:

+ + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
TransactionInactiveErrorThis IDBObjectStore's transaction is inactive.
DataError +

The key or key range provided contains and invalid key.

+
InvalidStateErrorThe IDBObjectStore has been deleted or removed.
+  
+ +

index()

+ +

Opens the named index in this object store.

+ +
IDBIndex index (in DOMString name) raises (DOMException);
+ +
Parameters
+ +
+
name
+
The name of the index to open.
+
+ +
Returns
+ +
+
IDBIndex
+
An object for accessing the index.
+
+ +
Exceptions
+ +

This method may raise a DOMException with a DOMError of the following types:

+ + + + + + + + + + + + + + + + + + +
ExceptionDescription
InvalidStateErrorThe source object store has been deleted, or the transaction for the object store has finished.
NotFoundErrorThere is no index with the given name (case-sensitive) in the database.
+  
+ +

openCursor()

+ +

Immediately returns an IDBRequest object, and creates a cursor over the records in this object store, in a separate thread. If there is even a single record that matches the key range, then a success event is fired on the returned object, with its result set to the IDBCursor object for the new cursor. If no records match the key range, then a success event is fired on the returned object, with its result set to null.

+ +
IDBRequest openCursor (in optional IDBKeyRange range, in optional unsigned short direction) raises(DOMException);
+ +
Parameters
+ +
+
range
+
The key range to use as the cursor's range. If this parameter is unspecified or null, then the range includes all the records in the object store.
+
direction
+
The cursor's direction.
+
+ +
Returns
+ +
+
IDBRequest
+
A request object on which subsequent events related to this operation are fired.
+
+ +
Exceptions
+ +

This method may raise a DOMException with a DOMError of the following types:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
TransactionInactiveErrorThis IDBObjectStore's transaction is inactive.
DataError +

The key or key range provided contains and invalid key.

+
InvalidStateErrorThe IDBObjectStore has been deleted or removed.
TypeErrorThe value of the direction parameter is invalid.
+ +

put()

+ +

Returns an IDBRequest object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. If the record is successfully stored, then a success event is fired on the returned request object with the result set to the key for the stored record, and transaction set to the transaction in which this object store is opened.

+ +

The put method is an update or insert method. See also the add() method.

+ +
IDBRequest put (in any value, in optional any key) raises (DOMException);
+ +
Parameters
+ +
+
value
+
The value to be stored.
+
key
+
The key to use to identify the record. If unspecified, it results to null.
+
+ +
Returns
+ +
+
IDBRequest
+
A request object on which subsequent events related to this operation are fired.
+
+ +
Exceptions
+ +

This method may raise a DOMException with a DOMError of the following types:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
ReadOnlyErrorThe transaction associated with this operation is in read-only mode.
TransactionInactiveErrorThis IDBObjectStore's transaction is inactive.
DataError +

Any of the following conditions apply:

+ +
    +
  • The object store uses in-line keys or has a key generator, and a key parameter was provided.
  • +
  • The object store uses out-of-line keys and has no key generator, and no key parameter was provided.
  • +
  • The object store uses in-line keys but no key generator, and the object store's key path does not yield a valid key.
  • +
  • The key parameter was provided but does not contain a valid key.
  • +
+
InvalidStateErrorThe IDBObjectStore has been deleted or removed.
DataCloneErrorThe data being stored could not be cloned by the internal structured cloning algorithm.
+ +

Example

+ +
+
+ +
+
+ +

This example shows a variety of different uses of object stores, from updating the data structure with {{domxref("IDBObjectStore.createIndex")}} inside an onupgradeneededfunction, to adding a new item to our object store with {{domxref("IDBObjectStore.add")}}. For a full working example, see our To-do Notifications app (view example live.)

+ +
// Let us open our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+DBOpenRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Database initialised.</li>';
+
+  // store the result of opening the database in db.
+  db = DBOpenRequest.result;
+};
+
+// This event handles the event whereby a new version of
+// the database needs to be created Either one has not
+// been created before, or a new version number has been
+// submitted via the window.indexedDB.open line above
+DBOpenRequest.onupgradeneeded = function(event) {
+  var db = event.target.result;
+
+  db.onerror = function(event) {
+    note.innerHTML += '<li>Error loading database.</li>';
+  };
+
+  // Create an objectStore for this database
+
+  var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" });
+
+  // define what data items the objectStore will contain
+
+  objectStore.createIndex("hours", "hours", { unique: false });
+  objectStore.createIndex("minutes", "minutes", { unique: false });
+  objectStore.createIndex("day", "day", { unique: false });
+  objectStore.createIndex("month", "month", { unique: false });
+  objectStore.createIndex("year", "year", { unique: false });
+
+  objectStore.createIndex("notified", "notified", { unique: false });
+
+  note.innerHTML += '<li>Object store created.</li>';
+};
+
+// Create a new item to add in to the object store
+var newItem = [
+  { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: 'December', year: 2013, notified: "no" }
+];
+
+// open a read/write db transaction, ready for adding the data
+var transaction = db.transaction(["toDoList"], "readwrite");
+
+// report on the success of the transaction completing, when everything is done
+transaction.oncomplete = function(event) {
+  note.innerHTML += '<li>Transaction completed.</li>';
+};
+
+transaction.onerror = function(event) {
+  note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+};
+
+// create an object store on the transaction
+var objectStore = transaction.objectStore("toDoList");
+// make a request to add our newItem object to the object store
+var objectStoreRequest = objectStore.add(newItem[0]);
+
+objectStoreRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Request successful .</li>';
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBObjectStore', 'IDBObjectStore')}}{{Spec2('IndexedDB')}}
{{SpecName("IndexedDB 2", "#object-store-interface", "IDBObjectStore")}}{{Spec2("IndexedDB 2")}}
+ +

Browser compatibility

+ +

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-dataand send us a pull request.

+ +

{{Compat("api.IDBObjectStore")}}

+ +

See also

+ + + +
diff --git a/files/zh-cn/web/api/idbobjectstore/indexnames/index.html b/files/zh-cn/web/api/idbobjectstore/indexnames/index.html new file mode 100644 index 0000000000..c124f70a9b --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/indexnames/index.html @@ -0,0 +1,110 @@ +--- +title: IDBObjectStore.indexNames +slug: Web/API/IDBObjectStore/indexNames +translation_of: Web/API/IDBObjectStore/indexNames +--- +

{{ APIRef("IndexedDB") }}

+ +
+

{{domxref("IDBObjectStore")}} 的只读属性 indexNames 返回此对象存储中对象的 indexes 名称(name)列表。

+ +

{{AvailableInWorkers}}

+
+ +

Syntax

+ +
var myindexNames = objectStore.indexNames;
+ +

Value

+ +

一个 {{domxref("DOMStringList")}}.

+ +

Example

+ +

在下面的代码片段中,我们在数据库上打开一个读/写事务并使用 add() 向对象存储添加一些数据。创建对象存储后,我们将打印 objectStore.indexNames 到控制台。有关完整的工作示例,请参阅我们的 待办事项通知应用程序 ( 实时查看示例 )

+ +
// 让我们来打开我们的数据库
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+DBOpenRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Database initialised.</li>';
+
+  // 将打开数据库的结果存储在db变量中
+  // 下面经常用到这个
+  db = this.result;
+
+  // 运行 addData() 函数将数据添加到数据库
+  addData();
+};
+
+function addData() {
+  // 创建一个新对象以准备插入到IDB中
+  var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ];
+
+  // 打开读/写数据库事务,准备添加数据
+  var transaction = db.transaction(["toDoList"], "readwrite");
+
+  // 当所有事情都完成时,报告事务完成的成功情况
+  transaction.oncomplete = function(event) {
+    note.innerHTML += '<li>Transaction completed.</li>';
+  };
+
+
+  transaction.onerror = function(event) {
+  note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+  };
+
+  // 在事务上创建对象存储
+  var objectStore = transaction.objectStore("toDoList");
+  console.log(objectStore.indexNames);
+
+  // 请求将 newItem 对象 添加到对象存储区
+  var objectStoreRequest = objectStore.add(newItem[0]);
+
+  objectStoreRequest.onsuccess = function(event) {
+    // 报告我们请求的成功
+    note.innerHTML += '<li>Request successful.</li>';
+  };
+};
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态解释
{{SpecName('IndexedDB', '#dom-idbobjectstore-indexnames', 'indexNames')}}{{Spec2('IndexedDB')}}
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-indexnames", "indexNames")}}{{Spec2("IndexedDB 2")}}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.IDBObjectStore.indexNames")}}

+
+ +

查看其它内容

+ + diff --git a/files/zh-cn/web/api/idbobjectstore/keypath/index.html b/files/zh-cn/web/api/idbobjectstore/keypath/index.html new file mode 100644 index 0000000000..e99f1ae519 --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/keypath/index.html @@ -0,0 +1,115 @@ +--- +title: IDBObjectStore.keyPath +slug: Web/API/IDBObjectStore/keyPath +translation_of: Web/API/IDBObjectStore/keyPath +--- +

{{ APIRef("IndexedDB") }}

+ +
+

{{domxref("IDBObjectStore")}}的只读属性keyPath接口返回当前objectStore的key path

+ +

什么是keyPath呢?在indexedDB中,一条记录就是一个object,object里面有一个属性作为这条记录的主要依据用来进行查询,而这个属性的属性名就是keyPath,属性值就是key。在用indexedDB的get方法时,提供key,而不需要指定keyPath,因为get方法把参数作为这个最主要的属性的值,在数据库中进行查询。(译者注)

+ +

如果该属性值为null,应用中必须在每一次进行修改性质的操作时提供一个key。

+ +

add、put方法都可以传第二个参数,当你当前的objectStore的autoIncrement为true时,你一般不会设置keyPath,如果这个时候你在put的时候不提供第二个参数,indexedDB就不知道要更新哪一条记录了。(译者注)

+
+ +

{{AvailableInWorkers}}

+ +

句法

+ +
var mykeyPath = objectStore.keyPath;
+ +

Value

+ +

任何类型。

+ +

例子

+ +

在下面代码片段中,我们在数据库里打开了一个可读写的事务(transaction),并且用add()向一个objectStore中添加了一些数据。在objectStore被创建之后,我们在console中打印了objectStore.keyPath的值。想查看完整的例子,请查看我们的To-do Notifications应用(查看在线例子)。

+ +
// Let us open our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+DBOpenRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Database initialised.</li>';
+
+  // store the result of opening the database in the db variable.
+  // This is used a lot below
+  db = DBOpenRequest.result;
+
+  // Run the addData() function to add the data to the database
+  addData();
+};
+
+function addData() {
+  // Create a new object ready to insert into the IDB
+  var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ];
+
+  // open a read/write db transaction, ready for adding the data
+  var transaction = db.transaction(["toDoList"], "readwrite");
+
+  // report on the success of the transaction completing, when everything is done
+  transaction.oncomplete = function(event) {
+    note.innerHTML += '<li>Transaction completed.</li>';
+  };
+
+  transaction.onerror = function(event) {
+  note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+  };
+
+  // create an object store on the transaction
+  var objectStore = transaction.objectStore("toDoList");
+  console.log(objectStore.keyPath);
+
+  // Make a request to add our newItem object to the object store
+  var objectStoreRequest = objectStore.add(newItem[0]);
+
+  objectStoreRequest.onsuccess = function(event) {
+    // report the success of our request
+    note.innerHTML += '<li>Request successful.</li>';
+  };
+};
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('IndexedDB', '#widl-IDBObjectStore-keyPath', 'keyPath')}}{{Spec2('IndexedDB')}} 
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-keypath", "keyPath")}}{{Spec2("IndexedDB 2")}} 
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.IDBObjectStore.keyPath")}}

+
+ +

相关内容

+ + diff --git a/files/zh-cn/web/api/idbobjectstore/opencursor/index.html b/files/zh-cn/web/api/idbobjectstore/opencursor/index.html new file mode 100644 index 0000000000..764582ad9a --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/opencursor/index.html @@ -0,0 +1,171 @@ +--- +title: IDBObjectStore.openCursor +slug: Web/API/IDBObjectStore/openCursor +translation_of: Web/API/IDBObjectStore/openCursor +--- +

{{ APIRef("IDBObjectStore") }}

+ +
+

{{domxref("IDBObjectStore")}} 的 openCursor() 方法 返回一个{{domxref("IDBRequest")}} 对象,并在一个单独的线程中,返回一个新的 {{domxref("IDBCursorWithValue")}} 对象。此方法目的是用一个游标来遍历一个对象存储空间。

+
+ +

若要确认此操作是否成功完成,请监听结果的 success 事件。

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var request = ObjectStore.openCursor(query, direction);
+ +

参数

+ +
+
query {{optional_inline}}
+
要查询的键或者 {{domxref("IDBKeyRange")}} 。如果传一个有效的键,则会默认为只包含此键的范围。如果此参数不传值,则默认为一个选择了该对象存储空间全部记录的键范围。
+
direction {{optional_inline}}
+
一个 {{domxref("IDBCursorDirection")}} 来告诉游标要移动的方向。有效的值有 "next" 、"nextunique" 、"prev" 和 "prevunique"。默认值是 "next"
+
+ +

返回

+ +

一个 {{domxref("IDBRequest")}} 对象,在此对象上触发与此操作相关的后续事件。

+ +

异常

+ +

此方法可能引起以下类型之一的 {{domxref("DOMException")}} :

+ + + + + + + + + + + + + + + + + + + + + + +
异常描述
InvalidStateError此 {{domxref("IDBObjectStore")}} 或{{domxref("IDBIndex")}} 已被删除。
TransactionInactiveError此 {{domxref("IDBObjectStore")}} 的事务处于非活动状态。
DataError指定的键或键范围无效。
+ +

例子

+ +

在下面这个简单的片段中,我们创建一个事务,检索一个对象存储空间,然后用一个游标去遍历该对象存储空间的所有记录:

+ +
var transaction = db.transaction("name", "readonly");
+var objectStore = transaction.objectStore("name");
+var request = objectStore.openCursor();
+request.onsuccess = function(event) {
+  var cursor = event.target.result;
+  if(cursor) {
+    // cursor.value 包含正在被遍历的当前记录
+    // 这里你可以对 result 做些什么
+    cursor.continue();
+  } else {
+    // 没有更多 results
+  }
+};
+
+
+ +

规范 

+ +
+
+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#widl-IDBIndex-openCursor-IDBRequest-any-range-IDBCursorDirection-direction', 'openCursor()')}}{{Spec2('IndexedDB')}} 
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-opencursor", "openCursor()")}}{{Spec2("IndexedDB 2")}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{property_prefix("webkit")}}
+ 24
10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10, partial157.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support4.4{{CompatGeckoMobile("22.0")}}1.0.11022{{CompatNo}}
+
+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/idbobjectstore/put/index.html b/files/zh-cn/web/api/idbobjectstore/put/index.html new file mode 100644 index 0000000000..368ea1d9a5 --- /dev/null +++ b/files/zh-cn/web/api/idbobjectstore/put/index.html @@ -0,0 +1,163 @@ +--- +title: IDBObjectStore.put() +slug: Web/API/IDBObjectStore/put +translation_of: Web/API/IDBObjectStore/put +--- +

{{ APIRef("IndexedDB") }}

+ +
+

 {{domxref("IDBObjectStore")}} 接口的  put() 方法更新一条给定的数据库记录,如果给出的值不存在,则插入一个新的记录

+ +

它返回一个 {{domxref("IDBRequest")}} 对象,并且在一个单独的线程 ,创建一个值的 structured clone ,并且把它的值储存在对象仓库(object store)中. 当事务的模式是readwrite时,这个方法用来添加新的记录,或者更新一条对象仓库(object store)中已存在的记录 . 如果记录被成功储存, then a success event is fired on the returned request object with the result set to the key for the stored record, and the transaction set to the transaction in which this object store is opened.

+
+ +

put方法是一个插入或更新对象仓库的方法. 参考仅用于插入的方法 {{domxref("IDBObjectStore.add")}} 方法.

+ +

谨记,如果你有一条 {{domxref("cursor","IDBCursor")}} 记录想要更新, 使用{{domxref("IDBCursor.update()")}} 方法更新,比 {{domxref("IDBObjectStore.put()")}} 方法更合适. 这样做可以清楚地表明将更新现有记录,而不是插入新记录.

+ +

{{AvailableInWorkers}}

+ +

语法

+ +
var request = objectStore.put(item);
+var request = objectStore.put(item, key);
+ +

参数

+ +
+
item
+
你想要更新 (或插入)的记录.
+
key {{optional_inline}}
+
你想要更新记录的主键 (e.g. from {{domxref("IDBCursor.primaryKey")}}). This is only needed for object stores that have an autoIncrement primary key, therefore the key is not in a field on the record object. In such cases, calling put(item) will always insert a new record, because it doesn't know what existing record you might want to modify.
+
+ +

返回值

+ +

一个 {{domxref("IDBRequest")}} 对象 ,在该对象上触发与此操作相关的后续事件。

+ +

异常

+ +

This method may raise a {{domxref("DOMException")}} of one of the following types:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExceptionDescription
ReadOnlyErrorThe transaction associated with this operation is in read-only mode.
TransactionInactiveErrorThis {{domxref("IDBObjectStore")}}'s transaction is inactive.
DataError +

Any of the following conditions apply:

+ +
    +
  • The object store uses in-line keys or has a key generator, and a key parameter was provided.
  • +
  • The object store uses out-of-line keys and has no key generator, and no key parameter was provided.
  • +
  • The object store uses in-line keys but no key generator, and the object store's key path does not yield a valid key.
  • +
  • The key parameter was provided but does not contain a valid key.
  • +
+
InvalidStateErrorThe {{domxref("IDBObjectStore")}} has been deleted or removed.
DataCloneErrorThe data being stored could not be cloned by the internal structured cloning algorithm.
+  
+ +

参数

+ +
+
value
+
被储存的值.
+
key
+
识别记录的键. 如果没有声明,那么记录键值将为空. 如果对象仓库有一个键生成器(e.g. autoincrement) ,必须传入key来更新对象.
+
+ +

Example

+ +

The following example requests a given record title; when that request is successful the onsuccess function gets the associated record from the {{domxref("IDBObjectStore")}} (made available as objectStoreTitleRequest.result), updates one property of the record, and then puts the updated record back into the object store in another request with put(). For a full working example, see our To-do Notifications app (view example live.)

+ +
var title = "Walk dog";
+
+// Open up a transaction as usual
+var objectStore = db.transaction(['toDoList'], "readwrite").objectStore('toDoList');
+
+// Get the to-do list object that has this title as it's title
+var objectStoreTitleRequest = objectStore.get(title);
+
+objectStoreTitleRequest.onsuccess = function() {
+  // Grab the data object returned as the result
+  var 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
+  var 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 = function() {
+    displayData();
+  };
+};
+ +

Specification

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#widl-IDBObjectStore-put-IDBRequest-any-value-any-key', 'put()')}}{{Spec2('IndexedDB')}}
{{SpecName("IndexedDB 2", "#dom-idbobjectstore-put", "put()")}}{{Spec2("IndexedDB 2")}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.IDBObjectStore.put")}}

+
+ +

See also

+ + -- cgit v1.2.3-54-g00ecf