--- 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); |
Attribute | Type | Description |
---|---|---|
indexNames |
readonly DOMStringList |
表中对象的索引名列表。 |
keyPath |
readonly DOMString |
表中的键路径,如果该属性为null,每次操作表时必须提供一个键名。 |
name |
readonly DOMString |
表名 |
transaction |
readonly IDBTransaction |
事务的名称,该表属于此事务。 |
autoIncrement |
readonly boolean |
表中自增字段的值 |
返回一个IDBRequest对象,并且在新线程中克隆一个值,该值存储在表中。
想知道是否成功添加数据,可以在事务的complete事件中进行监听,而不是success,因为事务在success事件之后还有可能失败。
add方法只能插入数据。如果以key参数作为某记录的关键字,并且该条记录已存在,则其所返回的请求对象会产生ConstrainError错误。
IDBRequest add (in any value, in optional any key) raises (DOMException);
该方法会抛出DOMError类型的DOMException异常。
Exception | Description |
---|---|
ReadOnlyError | The transaction associated with this operation is in read-only mode. |
TransactionInactiveError | This IDBObjectStore's transaction is inactive. |
DataError |
Any of the following conditions apply:
|
InvalidStateError |
The IDBObjectStore has been deleted or removed. |
DataCloneError |
The data being stored could not be cloned by the internal structured cloning algorithm. |
创建并立即返回一个 IDBRequest 对象, 并且在一个单独的线程中清除这个对象存储. 清除对象存储包括从对象存储中删除所有的记录,并删除对象存储引用的索引中的所有记录。
IDBRequest clear () raises (DOMException);
此方法可能会引发domException,其中domError的类型如下:
Exception | Description |
---|---|
ReadOnlyError | The transaction associated with this operation is in read-only mode. |
TransactionInactiveError | This IDBObjectStore's transaction is inactive. |
立即返回一个 IDBRequest 对象,并在新线程中计算符合条件的对象的数量,该方法的参数可以是键,或键范围(key range)。在 IDBRequest 对象中,source属性就是IDBObjectStore对象,result属性持有计算后的数量值。如果参数非法将会抛出异常。
IDBRequest count (in optional any key) raises
(DOMException);
该方法会引发如下异常:
Exception | Description |
---|---|
TransactionInactiveError | 事务已闲置 |
DataError |
key参数非法 |
InvalidStateError |
IDBObjectStore对象已被删除 |
创建并返回新的IDBIndex对象,该方法只能从versionchange事务模式的回调方法中被调用。
IDBIndex createIndex (in DOMString name, in
DOMString
keyPath, in optional boolean unique) raises (DOMException);
The IDBIndexParameters object whose attributes are optional parameters to the method. It includes the following properties:
Attribute | Description |
---|---|
unique |
If true, the index will not allow duplicate values for a single key. |
multiEntry |
If 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. |
This method may raise a DOMException with a DOMError of the following types:
Exception | Description |
---|---|
InvalidStateError |
The IDBObjectStore has been deleted or removed or the method was not called from a versionchange transaction mode callback. |
ConstraintError |
An index with the same name (case-sensitive) already exists in the database. |
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);
undefined
, so it's not possible to know if some records were actually deleted by looking at the request result.This method may raise a DOMException with a DOMError of the following types:
Exception | Description |
---|---|
TransactionInactiveError | This IDBObjectStore's transaction is inactive. |
ReadOnlyError |
The transaction associated with this operation is in read-only mode. |
DataError |
The 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);
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);
This method may raise a DOMException with a DOMError of the following types:
Exception | Description |
---|---|
InvalidStateError |
The method was not called from a versionchange transaction mode callback. |
NotFoundError |
There is no index with the given name (case-sensitive) in the database. |
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.") }}
IDBRequest
This method may raise a DOMException with a DOMError of the following types:
Exception | Description |
---|---|
TransactionInactiveError | This IDBObjectStore's transaction is inactive. |
DataError |
The key or key range provided contains and invalid key. |
InvalidStateError |
The IDBObjectStore has been deleted or removed. |
Opens the named index in this object store.
IDBIndex index (in
DOMString
name) raises (DOMException);
IDBIndex
This method may raise a DOMException with a DOMError of the following types:
Exception | Description |
---|---|
InvalidStateError |
The source object store has been deleted, or the transaction for the object store has finished. |
NotFoundError |
There is no index with the given name (case-sensitive) in the database. |
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);
IDBRequest
This method may raise a DOMException with a DOMError of the following types:
Exception | Description |
---|---|
TransactionInactiveError | This IDBObjectStore's transaction is inactive. |
DataError |
The key or key range provided contains and invalid key. |
InvalidStateError |
The IDBObjectStore has been deleted or removed. |
TypeError |
The value of the direction parameter is invalid. |
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);
This method may raise a DOMException with a DOMError of the following types:
Exception | Description |
---|---|
ReadOnlyError | The transaction associated with this operation is in read-only mode. |
TransactionInactiveError | This IDBObjectStore's transaction is inactive. |
DataError |
Any of the following conditions apply:
|
InvalidStateError |
The IDBObjectStore has been deleted or removed. |
DataCloneError |
The data being stored could not be cloned by the internal structured cloning algorithm. |
This example shows a variety of different uses of object stores, from updating the data structure with {{domxref("IDBObjectStore.createIndex")}} inside an onupgradeneeded
function, 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>';
}
Specification | Status | Comment |
---|---|---|
{{SpecName('IndexedDB', '#idl-def-IDBObjectStore', 'IDBObjectStore')}} | {{Spec2('IndexedDB')}} | |
{{SpecName("IndexedDB 2", "#object-store-interface", "IDBObjectStore")}} | {{Spec2("IndexedDB 2")}} |
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")}}