IDBObjectStore - Web API 接口参考 编辑

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

Note: 此特性在 Web Worker 中可用。

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

方法预览

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, inDOMStringkeyPath, in optional boolean unique) raises (DOMException);
IDBRequest delete (in any key) raises (DOMException);
void deleteIndex (in anyDOMStringindexName) raises (DOMException);
IDBRequest get (in any key) raises (DOMException);
IDBIndex index (inDOMStringname) 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表中对象的索引名列表。
keyPathreadonlyDOMString表中的键路径,如果该属性为null,每次操作表时必须提供一个键名。
namereadonlyDOMString表名
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 IDBObjectStore.createIndex inside an onupgradeneededfunction, to adding a new item to our object store with 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
Indexed Database API 2.0
IDBObjectStore
Recommendation
Indexed Database API Draft
IDBObjectStore
Recommendation

Browser compatibility

BCD tables only load in the browser

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.

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:82 次

字数:36909

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文