Indexeddb 简明教程

IndexedDB - Object Stores

Object stores 是 IndexedDB 的数据存储。这是存储数据的地方。数据库可以包含多个对象存储。可以将它们视为 RDBMS 中的表,在其中我们根据想要存储的数据类型存储数据。

Object stores are the data storage of IndexedDB. It is where data is stored. A database may have multiple object stores. Think of them as tables in RDBMS where we store data based on the type of data we want to store.

为了确保数据库完整性,只能使用回调函数 idb.open() 来创建和删除对象存储。它包含一个名为 createObjectStore() 的方法,用于创建对象存储。

To ensure database integrity, object stores can only be created and removed using the callback function idb.open(). It contains a method named createObjectStore() which is used to create an object-store.

Creating object Stores

可以使用 createObjectStore() 方法来创建对象存储。以下是此方法的语法 −

You can create an object store using the createObjectStore() method. Following is the syntax of this method −

IDBDatabase.createObjectStore(name);
Or,
IDBDatabase.createObjectStore(name, options);

其中,

Where,

  1. The name is the name of the object store.

  2. The options object can let us define various configuration properties.

Example

以下示例创建了一个新数据库并在其中创建了一个对象存储 −

Following example creates a new database and creates a object store in it −

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Creating Object Store</title>
</head>
<body>
   <script>
      var request = indexedDB.open("myDatabase", 2);
      request.onupgradeneeded = event => {
         var db = event.target.result;
         var objectStore = db.createObjectStore("customers");
         document.write("Object store Created Successfully...");
      };
   </script>
</body>
</html>

Output

执行时,上述程序会在浏览器上显示以下消息。

On executing, the above program displays the following message on the browser.

Object store Created Successfully...

Verification

如果上述程序执行成功,当您展开 “myDatabase” 时,您可以看到新创建的对象存储。

If the above program is executed successfully if you expand “myDatabase” you can see the newly created object-store.

customers file

Defining primary keys

类似于 RDBMS,我们需要主键来唯一地定义对象存储中的某些数据。可以使用密钥路径或密钥生成器以 2 种方式来实现这一点。

Similar to RDBMS we need primary keys to uniquely define some data in an object store. It can be done in 2 ways using a key path or a key generator.

Keypath and Key generator

key path 是总是存在的属性,并且包含惟一的值。我们可以选择一个惟一的值,如电子邮件地址。

A key path is a property that always exists and contains a unique value. We can choose a unique value such as an email address for example.

key generator 为添加到对象存储中的每个对象创建一个惟一的值。默认情况下,如果我们不提及密钥生成器则会进入该图像。例如,自动递增。

A key generator creates a unique value for every object added to the object store. By default, if we don’t mention a key generator comes into the picture. Ex, auto-increment.

Syntax

以下是对象存储上创建密钥路径的语法。

Following is the syntax ro create a keypath on an object store.

var objectStore = db.createObjectStore("ObjectStoreName", { keyPath: "primary key, autoincrement/autoDecrement : true" });

Example

在下面给出的示例中,我们正在使用 JavaScript 创建到对象存储的密钥路径 −

In the example given below, we are creating a keypath to an object store using JavaScript −

<!DOCTYPE html>
<html lang="en">
<head>
   <title>keypath</title>
</head>
<body>
   <script>
      var request = indexedDB.open("myDtabase", 2);
      request.onupgradeneeded = event => {
         var db = event.target.result;
         var objectStore = db.createObjectStore("customers",{keyPath:"id", autoIncrement:true});
         document.write("Object store Created Successfully...");
      };
   </script>
</body>
</html>

Output

执行上述示例后,它将在浏览器上显示以下文本 −

On executing the above example, it will display the following text on the browser −

Object store Created Successfully...

Verification

如果上述程序执行成功,当您展开 “myDatabase” 时,您可以看到新创建的对象存储,如果单击它,则可以看到为 “id” 创建了密钥路径。

If the above program is executed successfully if you expand “myDatabase” you can see the newly created object store, if you click on it you can observe that the keypath is created for “id”.

key path

创建新的对象存储时,它们会像上面一样在 IndexedDB 文件夹中提及。

When new object stores are created they are mentioned in the IndexedDB folders like above.

你可以同时使用键路径和键生成器。如果数据总能是唯一的,我们可以使用一个 keypath,否则如果值更改,你可以使用一个键生成器,如果你想为每一个值更改值,但希望提供唯一地表示存储的值,我们可以两个都用。

You can use both a keypath and a key generator. If the data is always unique we can use a keypath else if the value changes you can use a key generator, if you want to change the values for every value but want to give a value that uniquely represents the store we can use both.

Defining Indexes

索引是一种对象存储。它们用于从存储在指定属性中的引用对象检索数据。索引使用指定属性作为其键路径,而不是引用存储的主键。

Indexes are a kind of object-store. They are used to retrieve data from the reference object, stored by a specified property. An index uses the specified property as its key path instead of the reference store’s primary key.

要创建索引,你需要在 createIndex() 实例上调用 object store 方法。

To create an index, you need to call the createIndex() method on an object store instance.

Syntax

下面是 createIndex() 方法的语法 −

Following is the syntax of the createIndex() method −

var myIDBIndex = objectStore.createIndex(indexName, keyPath);
var myIDBIndex = objectStore.createIndex(indexName, keyPath, Parameters);

其中,

Where,

  1. An indexName is the name of the index created.

  2. Keypath is the primary definition while creating an object store

  3. The value of the last parameter can be unique or multi-entry In case you “pass unique: true”. The index will not allow duplicate values for a single key. If you pass “multi-entry: true”. The index will add an entry for each array element when the keyPath resolves to an Array. If false, it will add one single entry containing the Array.

Example

以下 JavaScript 示例演示如何创建索引。

The following JavaScript example demonstrates how to create indexes.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>OPENING A DATABASE</title>
</head>
<body>
   <script>
      const dbName = "myDB";
      const studentdata = [
         {name : "jason" , rollno: "160218737028" , branch : "IT"},
         {name : "lokesh" , rollno: "160218735020" , branch : "CSE"},
         {name : "tarun" , rollno: "160218733057" , branch : "EEE"},
         {name : "pranith" , rollno: "160218737029" , branch : "IT"}
      ];
      var request = indexedDB.open("myDB", 2);
      request.onupgradeneeded = event => {
         var db = event.target.result;
         var objectStore = db.createObjectStore("student",{ keyPath :"rollno" });
         objectStore.createIndex("name", "name", { unique: false });
         objectStore.createIndex("branch", "branch", { unique: false });
         objectStore.transaction.oncomplete = event => {
            var objectStore = db.transaction("student", "readwrite").objectStore("student");
            studentdata.forEach(function(student) {
               objectStore.add(student);
            });
         };
      };
   </script>
</body>
</html>

Output

如果您去验证 IndexedDB 数据库 myDB 的内容并展开它,您将观察被创建的表如下 −

If you go and verify the contents of the IndexedDB database myDB and expand it youj can observe the created table as −

key values

如果您点击名称和学生值,您将观察索引值如下 −

If you click on the name and student values you can observe the index values as −

Name index

Name index

#

Key(Key path:"name")

Primary key (Key path:"rollno")

Value

0

"jason"

"160218737028"

{name: 'jason', rollno: '160218737028', branch: 1. branch: "IT" 2. name: "jason" 3. rollno: "160218737028"

1

"lokesh"

"160218735020"

{name: 'lokesh', rollno: '160218735020', branch: 'CSE'} 1. branch: "CSE" 2. name: "lokesh" 3. rollno: "160218735020"

2

"pranith"

"160218737029"

{name: 'pranith', rollno: '160218737029', branch: 'IT'} 1. branch: "IT" 2. name: "pranith" 3. rollno: "160218737029"

3

"tarun"

"160218733057"

{name: 'tarun', rollno: '160218733057', branch: 'EEE'} 1. branch: "EEE" 2. name: "tarun" 3. rollno: "160218733057"

Branch Index

Branch Index

#

Key(Key path:"branch")

Primary key (Key path:"rollno")

Value

0

"CSE"

"160218735020"

{name:'lokesh', rollno:'160218735020', branch: 'CSE'} 1. branch: "CSE" 2. name: "lokesh" 3. rollno: "160218735020"

1

"EEE"

"160218733057"

{name:'tarun', rollno: '160218733057', branch: 'EEE'} 1. branch: "EEE" 2. name: "tarun" 3. rollno: "160218733057"

2

"IT"

"160218737028"

{name:'jason', rollno: '160218737028', branch: 'IT'} 1. branch: "IT" 2. name: "jason" 3. rollno: "160218737028"

3

"IT"

"160218737029"

{name:'pranith', rollno: '160218737029', branch: 'IT'} 1. branch: "IT" 2. name: "pranith" 3. rollno: "160218737029"

Deleting Object Store

对象存储与数据库中的表类似,当不需要该表时,我们可以删除表。类似地,当不再使用对象存储时,您可以删除该对象存储。要删除对象存储,您需要调用 deleteObjectStore() 函数。

Object stores are similar to tables in a database and when a table is not needed we delete it. Similarly, you can delete an object store if it is no longer in use. To delete the object store you need to invoke the deleteObjectStore() function.

Syntax

以下是 deleteObjectStore() 函数的语法 −

Following is the syntax of the deleteObjectStore() function −

db.deleteObjectStore("store_name");

其中,store_name是您需要删除的对象存储的名称。

Where, store_name is the name of the object store you need to delete.

Example

让我们看一个删除不再必需的对象存储的 JavaScript 示例 −

Let us look at a JavaScript example that deletes an object store which is no longer necessary −

<!DOCTYPE html>
<html lang="en">
<head>
   <title>OPENING A DATABASE</title>
</head>
<body>
   <script>
      const dbName = "Database";
      var request = indexedDB.open("Database", 2);
      request.onupgradeneeded = event => {
         var db = event.target.result;
         var objectStore = db.createObjectStore("student",{ keyPath :"rollno" } );
         var objstore = db.createObjectStore("college",{autoIncrement : true});
         db.deleteObjectStore("college");
      };
   </script>
</body>
</html>

Output

在浏览器的 IndexedDB 文件夹中删除对象存储之前和之后。

Before and After deleting the object store in the IndexedDB folder in the browser.

Database
   College − object store
   Student − object store
      Name − index
      Branch − index

Database
   Student − object store
      Name − index
      Branch − index