HTML (016) HTML5 IndexedDB 索引数据库(HTML (016) HTML5 indexeddb index database)

一、诞生背景:

随着浏览器的功能不断增强,越来越多的网站开始考虑,将大量数据储存在客户端,这样可以减少从服务器获取数据,直接从本地获取数据。现有的浏览器数据储存方案,都不适合储存大量数据:Cookie
的大小不超过4KB,且每次请求都会发送回服务器;LocalStorage 在 2.5MB 到 10MB
之间(各家浏览器不同),而且不提供搜索功能,不能建立自定义的索引。所以,需要一种新的解决方案,这就是 IndexedDB 诞生的背景。

IndexedDB是浏览器提供的本地数据库, 允许储存大量数据,提供查找接口,还能建立索引。这些都是 LocalStorage
所不具备的。就数据库类型而言,IndexedDB 不属于关系型数据库(不支持 SQL 查询语句),更接近 NoSQL 数据库。

IndexedDB里数据以对象的形式存储,每个对象都有一个key值索引。IndexedDB里的操作都是事务性的。一种对象存储在一个objectStore里,objectStore就相当于关系数据库里的表。IndexedDB可以有很多objectStore,objectStore里可以有很多对象。每个对象可以用key值获取。

二、特点:

  • 键值对储存。 IndexedDB 内部采用对象仓库(object store)存放数据。所有类型的数据都可以直接存入,包括 JavaScript 对象。对象仓库中,数据以”键值对”的形式保存,每一个数据记录都有对应的主键,主键是独一无二的,不能有重复,否则会抛出一个错误。
  • 异步。 IndexedDB 操作时不会锁死浏览器,用户依然可以进行其他操作,这与 LocalStorage 形成对比,后者的操作是同步的。异步设计是为了防止大量数据的读写,拖慢网页的表现。
  • 支持事务。 IndexedDB 支持事务(transaction),这意味着一系列操作步骤之中,只要有一步失败,整个事务就都取消,数据库回滚到事务发生之前的状态,不存在只改写一部分数据的情况。
  • 同源限制。 IndexedDB 受到同源限制,每一个数据库对应创建它的域名。网页只能访问自身域名下的数据库,而不能访问跨域的数据库。
  • 储存空间大。 IndexedDB 的储存空间比 LocalStorage 大得多,一般来说不少于 250MB,甚至没有上限。
  • 支持二进制储存。 IndexedDB 不仅可以储存字符串,还可以储存二进制数据(ArrayBuffer 对象和 Blob 对象)。

三、基本概念:

  • 数据库。IDBDatabase 对象
    数据库是一系列相关数据的容器。每个域名(严格的说,是协议 + 域名 + 端口)都可以新建任意多个数据库。
    IndexedDB
    数据库有版本的概念。同一个时刻,只能有一个版本的数据库存在。如果要修改数据库结构(新增或删除表、索引或者主键),只能通过升级数据库版本完成。
  • 对象仓库。IDBObjectStore 对象
    每个数据库包含若干个对象仓库(object store)。它类似于关系型数据库的表格。
  • 数据记录。IDBKeyRange 对象
    对象仓库保存的是数据记录。每条记录类似于关系型数据库的行,但是只有主键和数据体两部分。主键可以是数据记录里面的一个属性,也可以指定为一个递增的整数编号。
  • 索引。IDBIndex 对象
  • 事务。IDBTransaction 对象
    数据记录的读写和删改,都要通过事务完成。事务对象提供error、abort和complete三个事件,用来监听操作结果。
  • 操作请求:IDBRequest 对象。 几乎是所有 indexedDB 操作的返回值,indexedDB 操作请求
    IDBRequest.result 结果
    IDBRequest.onerror 异常事件
    IDBRequest.onsuccess 成功的事件
  • 指针: IDBCursor 对象

四、indexedDB 对比 LocalStorage

IndexedDB和LocalStorage都是用来在浏览器里存储数据,但它们使用不同的技术,有不同的用途,你需要根据自己的情况适当的选择使用哪种。LocalStorage是用key-
value键值模式存储数据,但跟IndexedDB不一样的是,它的数据并不是按对象形式存储。它存储的数据都是字符串形式。如果你想让LocalStorage存储对象,你需要借助能将对象变成字符串形式,再用将字符串还原成对象。但如果要存储大量的复杂的数据,这并不是一种很好的方案。毕竟,localstorage就是专门为小数量数据设计的,它的api是同步的。

JSON.stringify()
JSON.parse()

IndexedDB很适合存储大量数据,它的API是异步调用的。IndexedDB使用索引存储数据,各种数据库操作放在事务中执行。IndexedDB甚至还支持简单的数据类型。IndexedDB比localstorage强大得多,但它的API也相对复杂。

对于简单的数据,你应该继续使用localstorage,但当你希望存储大量数据时,IndexedDB会明显的更适合,IndexedDB能提供你更为复杂的查询数据的方式。

五、基本操作:

1、浏览器是否支持:

    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    
    if(!window.indexedDB){
        console.log("你的浏览器不支持IndexedDB");
    }

2、打开数据库&新建数据库

新建数据库与打开数据库是同一个操作。如果指定的数据库不存在,就会新建。不同之处在于,后续的操作主要在事件的监听函数里面完成,因为这时版本从无到有,所以会触发这个事件。

upgradeneeded

一旦你的浏览器支持IndexedDB,我们就可以打开它。但不能直接打开IndexedDB数据库。IndexedDB需要你创建一个请求来打开它。

使用 IndexedDB 的第一步是打开数据库,使用方法。

indexedDB.open()
    var request = window.indexedDB.open(databaseName, version);

这个方法接受两个参数,第一个参数是字符串,表示数据库的名字。如果指定的数据库不存在,就会新建数据库。第二个参数是整数,表示数据库的版本。如果省略,打开已有数据库时,默认为当前版本;新建数据库时,默认为。

1

如果没有版本号变化,而且页面之前被打开过,你会获得一个事件。如果有错误发生时则触发事件。如果你之前没有关闭连接,则会触发事件。

onsuccess
onerror
onblocked

方法返回一个 IDBRequest
对象。这个对象通过三种事件、、,处理打开数据库的操作结果。

indexedDB.open()
error
success
upgradeneeded

事件在第一次打开页面初始化数据库时会被调用,或在当有版本号变化时被调用。所以,你应该在函数里创建你的存储数据。通过事件对象的属性,拿到数据库实例。

onupgradeneeded
onupgradeneeded
target.result

通常,新建数据库以后,第一件事是新建对象仓库objectStore(即新建表)。一个objectStore相当于一张表,里面存储的每条数据和一个键相关联。

表中的主键(key)是默认建立索引的属性。比如,数据记录是,那么属性可以作为主键。

{ id: 1, name: '张三' }
id
    db.createObjectStore('students',{keyPath:"id"});

主键也可以指定为下一层对象的属性,比如的也可以指定为主键。

{ foo: { bar: 'baz' } }
foo.bar

如果数据记录里面没有合适作为主键的属性,那么可以让 IndexedDB 自动生成主键。

    db.createObjectStore('students',{autoIncrement: true});

eg:数据库新建成功以后,新增一张叫做的表格,主键是。

person
id
    var db;
    var objectStore;
    var request = window.indexedDB.open("testDB", 2);
    
    request.onerror = function (event) {}
    
    
    request.onsuccess = function (event) {
        db = request.result//可以拿到数据库对象
    }
    //如果指定的版本号,大于数据库的实际版本号,就会发生数据库升级事件upgradeneeded
    request.onupgradeneeded = function (event) {
        db = event.target.result;
        if (!db.objectStoreNames.contains('person')) {//判断表是否存在
            objectStore = db.createObjectStore('person', { keyPath: 'id' }); //创建表
        //自动生成主键db.createObjectStore(
        //  'person',
        //  { autoIncrement: true }
        //);
        }
        //新建索引,参数索引名称、索引所在的属性、配置对象
        objectStore.createIndex('email', 'email', { unique: true });
    }

3、关闭、删除数据库

关闭数据库可以直接调用数据库对象的close方法。

删除数据库使用indexedDB对象的deleteDatabase方法。

    function openDB (name,version) {
                var version=version || 1;
                var request=window.indexedDB.open(name,version);
                request.onerror=function(e){
                    console.log(e.currentTarget.error.message);
                };
                request.onsuccess=function(e){
                    myDB.db=e.target.result;
                };
                request.onupgradeneeded=function(e){
                    console.log('DB version changed to '+version);
                };
            }
    
    function closeDB(db){
                db.close();
            }
    
    function deleteDB(name){
                indexedDB.deleteDatabase(name);
            }
    
    var myDB={
                name:'test',
                version:3,
                db:null
    };
     
    openDB(myDB.name,myDB.version);
    setTimeout(function(){
                closeDB(myDB.db);
                deleteDB(myDB.name);
    },500);

4、新增数据

为了往数据库里新增数据,我们首先需要创建一个事务,并要求具有读写权限。在indexedDB里任何的存取对象的操作都需要放在事务里执行。

新建事务时必须指定表格名称和操作模式(”只读”或”读写”)。新建事务以后,通过方法,拿到
IDBObjectStore 对象,再通过表格对象的方法,向表格写入一条记录。

IDBTransaction.objectStore(name)
add()

写入操作是一个异步操作,通过监听连接对象的事件和事件,了解是否写入成功。

success
error
    function add() {
      var request = db.transaction(['person'], 'readwrite')
        .objectStore('person')
        .add({ id: 1, name: '张三', age: 24, email: 'zhangsan@example.com' });
    
      request.onsuccess = function (event) {
        console.log('数据写入成功');
      };
    
      request.onerror = function (event) {
        console.log('数据写入失败');
      }
    }
    
    add();

5、读取数据

方法用于读取数据,参数是主键的值。

objectStore.get()

通过key取出对象,即往方法里传入对象的key值,取出相应的对象。

get()
    function read() {
       var transaction = db.transaction(['person']);
       var objectStore = transaction.objectStore('person');
       var request = objectStore.get(1);
    
    
       console.log(request.id);
    
    
    
       request.onerror = function(event) {
         console.log('事务失败');
       };
    
       request.onsuccess = function( event) {
          if (request.result) {
            console.log('Name: ' + request.result.name);
            console.log('Age: ' + request.result.age);
            console.log('Email: ' + request.result.email);
          } else {
            console.log('未获得数据记录');
          }
       };
    }
    
    read();

6、数据更新

方法。

IDBObject.put()

方法自动更新了主键为的记录。

以下代码使用put()
1
    function update() {
      var request = db.transaction(['person'], 'readwrite')
        .objectStore('person')
        .put({ id: 1, name: '李四', age: 35, email: 'lisi@example.com' });
    
      request.onsuccess = function (event) {
        console.log('数据更新成功');
      };
    
      request.onerror = function (event) {
        console.log('数据更新失败');
      }
    }
    
    update();

为了更新一个对象,首先要把它取出来,修改,然后再放回去。

    var transaction = db.transaction(["students"],"readwrite");
    var objectStore = transaction.objectStore("students");
    var request = objectStore.get(rollNo);
    request.onsuccess = function(event){
        console.log("Updating : "+request.result.name + " to " + name);
        request.result.name = name;
        objectStore.put(request.result);
    };

7、数据删除

方法用于删除记录。

IDBObjectStore.delete()

删除跟新增一样,需要创建事务,然后调用删除接口,通过key删除对象。

    function remove() {
      var request = db.transaction(['person'], 'readwrite')
        .objectStore('person')
        .delete(1);
    
      request.onsuccess = function (event) {
        console.log('数据删除成功');
      };
    }
    
    remove();

1、调用object store的clear方法可以清空object store

    function clearObjectStore(db,storeName){
                var transaction=db.transaction(storeName,'readwrite'); 
                var store=transaction.objectStore(storeName); 
                store.clear();
    }

2、调用数据库实例的deleteObjectStore方法可以删除一个object store。

这个就得在onupgradeneeded里面调用了。

    if(db.objectStoreNames.contains('students')){ 
                        db.deleteObjectStore('students'); 
    }

8、索引的使用

添加索引后可以使用索引查询数据

索引的意义在于,可以让你搜索任意字段,也就是说从任意字段拿到数据记录。如果不建立索引,默认只能搜索主键(即从主键取值)。

假定新建表格的时候,对字段建立了索引。

name

新建索引。的三个参数分别为索引名称、索引所在的属性、配置对象(说明该属性是否包含重复的值)。

IDBObject.createIndex()
    objectStore.createIndex('name', 'name', { unique: false });

现在,就可以从找到对应的数据记录了。

name
    var transaction = db.transaction(['person'], 'readonly');
    var store = transaction.objectStore('person');
    var index = store.index('name');
    var request = index.get('李四');
    
    request.onsuccess = function (e) {
      var result = e.target.result;
      if (result) {
        // ...
      } else {
        // ...
      }
    }

9、遍历数据

遍历数据表格的所有记录,要使用指针对象 IDBCursor。

方法是一个异步操作,所以要监听事件。

openCursor()
success

curson.contine()会使游标下移,直到没有数据返回undefined

index.openCursor()/``index.openKeyCursor()方法:在不传递参数的时候会获取object store所有记录
    function readAll() {
      var objectStore = db.transaction('person').objectStore('person');
    
         var request= objectStore.openCursor()
    
    
         request.onsuccess = function (event) {
         var cursor = event.target.result;
    
         if (cursor) {
           console.log('Id: ' + cursor.key);
           console.log('Name: ' + cursor.value.name);
           console.log('Age: ' + cursor.value.age);
           console.log('Email: ' + cursor.value.email);
           cursor.continue();
        } else {
          console.log('没有更多数据了!');
        }
      };
    }
    
    readAll();

指定游标范围

可以使用key range 限制游标中值的范围,把它作为第一个参数传给 或是

openCursor()
openKeyCursor()
  • IDBKeyRange.only(value):只获取指定数据
  • “`IDBKeyRange.lowerBound(value,isOpen):获取最小是value的数据,第二个参数用来指示是否排除value值本身,也就是数学中的是否是开区间`
  • IDBKeyRange.upperBound(value,isOpen):和上面类似,用于获取最大值是value的数据
  • IDBKeyRange.bound(value1,value2,isOpen1,isOpen2):不用解释了吧

要想获取age为26的student,可以结合游标使用索引

    function getMultipleData(db,storeName){
                var transaction=db.transaction(storeName);
                var store=transaction.objectStore(storeName);
                var index = store.index("ageIndex");
                var request=index.openCursor(IDBKeyRange.only(26))
                request.onsuccess=function(e){
                    var cursor=e.target.result;
                    if(cursor){
                        var student=cursor.value;
                        console.log(student.id);
                        cursor.continue();
                    }
                }
            }

获取名字首字母在B-E的student

    function getMultipleData(db,storeName){
                var transaction=db.transaction(storeName);
                var store=transaction.objectStore(storeName);
                var index = store.index("nameIndex");
                var request=index.openCursor(IDBKeyRange.bound('B','F',false,true));
                request.onsuccess=function(e){
                    var cursor=e.target.result;
                    if(cursor){
                        var student=cursor.value;
                        console.log(student.name);
                        cursor.continue();
                    }
                }
            }
————————

1、 Birth background:

With the increasing function of the browser, more and more websites begin to consider storing a large amount of data on the client, which can reduce the need to obtain data from the server and directly obtain data locally. The existing browser data storage schemes are not suitable for storing a large amount of data: cookies
The size of is no more than 4KB, and each request will be sent back to the server; Localstorage is between 2.5Mb and 10MB
Between (different browsers), and does not provide search function, can not establish a user-defined index. Therefore, a new solution is needed, which is the background of the birth of indexeddb.

Indexeddb is a local database provided by the browser. It allows to store a large amount of data, provides a search interface, and can also establish an index. These are localstorage
What you don’t have. In terms of database type, indexeddb is not a relational database (SQL query statements are not supported), which is closer to NoSQL database.

The data in indexeddb is stored in the form of objects, and each object has a key value index. All operations in indexeddb are transactional. An object is stored in an objectstore, which is equivalent to a table in a relational database. Indexeddb can have many objectstores, and there can be many objects in the objectstore. Each object can be obtained with the key value.

2、 Features:

  • Key value pair storage. Indexeddb uses an object store to store data. All types of data can be stored directly, including JavaScript objects. In the object warehouse, data is saved in the form of “key value pairs”. Each data record has a corresponding primary key. The primary key is unique and cannot be repeated, otherwise an error will be thrown.
  • Asynchronous. Indexeddb will not lock the browser during operation, and users can still perform other operations, which is in contrast to localstorage, which operates synchronously. Asynchronous design is to prevent reading and writing of a large amount of data and slow down the performance of web pages.
  • Support transactions. Indexeddb supports transactions, which means that in a series of operation steps, as long as one step fails, the whole transaction will be cancelled, and the database will be rolled back to the state before the transaction. There is no case that only part of the data is overwritten.
  • Homology restriction. Indexeddb is restricted by homology, and each database corresponds to the domain name that created it. Web pages can only access the database under their own domain name, but can not access the cross domain database.
  • Large storage space. The storage space of indexeddb is much larger than that of localstorage. Generally speaking, it is no less than 250MB, or even no upper limit.
  • Support binary storage. Indexeddb can store not only strings, but also binary data (arraybuffer object and blob object).

3、 Basic concepts:

  • database Idbdatabase object
    A database is a container for a series of related data. Each domain name (strictly speaking, protocol + domain name + port) can create any number of databases.
    IndexedDB
    Database has the concept of version. At the same time, only one version of the database can exist. If you want to modify the database structure (add or delete tables, indexes or primary keys), you can only upgrade the database version.
  • Warehouse object. Idbobjectstore object
    Each database contains several object stores. It is similar to a table in a relational database.
  • Data recording. Idbkeyrange object
    The object warehouse stores data records. Each record is similar to the row of a relational database, but only has two parts: the primary key and the data body. A primary key can be an attribute in a data record, or it can be specified as an increasing integer number.
  • 索引。IDBIndex 对象
  • Business. Idbtransaction object
    The reading, writing, deletion and modification of data records should be completed through transactions. The transaction object provides three events: error, abort and complete, which are used to listen for operation results.
  • 操作请求:IDBRequest 对象。 几乎是所有 indexedDB 操作的返回值,indexedDB 操作请求
    IDBRequest.result 结果
    IDBRequest.onerror 异常事件
    IDBRequest.onsuccess 成功的事件
  • 指针: IDBCursor 对象

四、indexedDB 对比 LocalStorage

Indexeddb and localstorage are both used to store data in the browser, but they use different technologies and have different purposes. You need to choose which one to use according to your own situation. Localstorage uses key-
The value key mode stores data, but unlike indexeddb, its data is not stored as an object. It stores data in string form. If you want localstorage to store objects, you need to be able to turn the object into a string, and then restore the string to an object. But if you want to store a large number of complex data, this is not a good solution. After all, localstorage is specifically designed for small amounts of data, and its API is synchronous.

JSON.stringify()
JSON.parse()

Indexeddb is suitable for storing large amounts of data, and its API is called asynchronously. Indexeddb uses indexes to store data, and various database operations are executed in transactions. Indexeddb even supports simple data types. Indexeddb is much more powerful than localstorage, but its API is also relatively complex.

For simple data, you should continue to use local storage, but when you want to store a large amount of data, indexeddb is obviously more suitable. Indexeddb can provide you with a more complex way to query data.

5、 Basic operation:

1. Does the browser support:

    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    
    if(!window.indexedDB){
        console.log("你的浏览器不支持IndexedDB");
    }

2. Open database & new database

Creating a new database is the same operation as opening a database. If the specified database does not exist, it will be created. The difference is that the subsequent operations are mainly completed in the event listening function, because the version is from scratch, so this event will be triggered.

upgradeneeded

Once your browser supports indexeddb, we can open it. However, the indexeddb database cannot be opened directly. Indexeddb requires you to create a request to open it.

The first step in using indexeddb is to open the database and use the method.

indexedDB.open()
    var request = window.indexedDB.open(databaseName, version);

This method accepts two parameters. The first parameter is a string representing the name of the database. If the specified database does not exist, a new database will be created. The second parameter is an integer that represents the version of the database. If omitted, when opening an existing database, it defaults to the current version; When creating a new database, the default is.

1

If there is no version number change and the page has been opened before, you will get an event. An event is triggered if an error occurs. If you have not closed the connection before, an event will be triggered.

onsuccess
onerror
onblocked

Method returns an idbrequest
Object. This object handles the operation results of opening the database through three events.

indexedDB.open()
error
success
upgradeneeded

Event is called when the page is first opened to initialize the database, or when the version number changes. Therefore, you should create your stored data in the function. Get the database instance through the properties of the event object.

onupgradeneeded
onupgradeneeded
target.result

Usually, after creating a new database, the first thing is to create an object warehouse objectstore (that is, create a new table). An objectstore is equivalent to a table in which each data stored is associated with a key.

The primary key in the table is the attribute for indexing by default. For example, if the data record is, the attribute can be used as the primary key.

{ id: 1, name: '张三' }
id
    db.createObjectStore('students',{keyPath:"id"});

The primary key can also be specified as the attribute of the next level object. For example, it can also be specified as the primary key.

{ foo: { bar: 'baz' } }
foo.bar

If there are no attributes suitable for the primary key in the data record, indexeddb can automatically generate the primary key.

    db.createObjectStore('students',{autoIncrement: true});

Eg: after the database is created successfully, a new table called is added. The primary key is.

person
id
    var db;
    var objectStore;
    var request = window.indexedDB.open("testDB", 2);
    
    request.onerror = function (event) {}
    
    
    request.onsuccess = function (event) {
        db = request.result//可以拿到数据库对象
    }
    //如果指定的版本号,大于数据库的实际版本号,就会发生数据库升级事件upgradeneeded
    request.onupgradeneeded = function (event) {
        db = event.target.result;
        if (!db.objectStoreNames.contains('person')) {//判断表是否存在
            objectStore = db.createObjectStore('person', { keyPath: 'id' }); //创建表
        //自动生成主键db.createObjectStore(
        //  'person',
        //  { autoIncrement: true }
        //);
        }
        //新建索引,参数索引名称、索引所在的属性、配置对象
        objectStore.createIndex('email', 'email', { unique: true });
    }

3. Close and delete database

When you close the database, you can directly call the close method of the database object.

Deleting a database uses the deletedatabase method of the indexeddb object.

    function openDB (name,version) {
                var version=version || 1;
                var request=window.indexedDB.open(name,version);
                request.onerror=function(e){
                    console.log(e.currentTarget.error.message);
                };
                request.onsuccess=function(e){
                    myDB.db=e.target.result;
                };
                request.onupgradeneeded=function(e){
                    console.log('DB version changed to '+version);
                };
            }
    
    function closeDB(db){
                db.close();
            }
    
    function deleteDB(name){
                indexedDB.deleteDatabase(name);
            }
    
    var myDB={
                name:'test',
                version:3,
                db:null
    };
     
    openDB(myDB.name,myDB.version);
    setTimeout(function(){
                closeDB(myDB.db);
                deleteDB(myDB.name);
    },500);

4. New data

In order to add data to the database, we first need to create a transaction and have read-write permission. In indexeddb, any operation to access the object needs to be executed in the transaction.

When creating a new transaction, you must specify the table name and operation mode (read-only or read-write). After creating a new transaction, you can get it through the method
Idbobjectstore object, and then write a record to the table through the method of table object.

IDBTransaction.objectStore(name)
add()

Write operation is an asynchronous operation. You can know whether the write is successful by listening to the events and events of the connection object.

success
error
    function add() {
      var request = db.transaction(['person'], 'readwrite')
        .objectStore('person')
        .add({ id: 1, name: '张三', age: 24, email: 'zhangsan@example.com' });
    
      request.onsuccess = function (event) {
        console.log('数据写入成功');
      };
    
      request.onerror = function (event) {
        console.log('数据写入失败');
      }
    }
    
    add();

5. Read data

Method is used to read data, and the parameter is the value of the primary key.

objectStore.get()

Get the object through the key, that is, pass the key value of the object into the method to get the corresponding object.

get()
    function read() {
       var transaction = db.transaction(['person']);
       var objectStore = transaction.objectStore('person');
       var request = objectStore.get(1);
    
    
       console.log(request.id);
    
    
    
       request.onerror = function(event) {
         console.log('事务失败');
       };
    
       request.onsuccess = function( event) {
          if (request.result) {
            console.log('Name: ' + request.result.name);
            console.log('Age: ' + request.result.age);
            console.log('Email: ' + request.result.email);
          } else {
            console.log('未获得数据记录');
          }
       };
    }
    
    read();

6. Data update

method.

IDBObject.put()

Method automatically updates the record with primary key.

以下代码使用put()
1
    function update() {
      var request = db.transaction(['person'], 'readwrite')
        .objectStore('person')
        .put({ id: 1, name: '李四', age: 35, email: 'lisi@example.com' });
    
      request.onsuccess = function (event) {
        console.log('数据更新成功');
      };
    
      request.onerror = function (event) {
        console.log('数据更新失败');
      }
    }
    
    update();

In order to update an object, first take it out, modify it, and then put it back.

    var transaction = db.transaction(["students"],"readwrite");
    var objectStore = transaction.objectStore("students");
    var request = objectStore.get(rollNo);
    request.onsuccess = function(event){
        console.log("Updating : "+request.result.name + " to " + name);
        request.result.name = name;
        objectStore.put(request.result);
    };

7. Data deletion

Method is used to delete a record.

IDBObjectStore.delete()

Deleting is the same as adding. You need to create a transaction, and then call the delete interface to delete the object through the key.

    function remove() {
      var request = db.transaction(['person'], 'readwrite')
        .objectStore('person')
        .delete(1);
    
      request.onsuccess = function (event) {
        console.log('数据删除成功');
      };
    }
    
    remove();

1、调用object store的clear方法可以清空object store

    function clearObjectStore(db,storeName){
                var transaction=db.transaction(storeName,'readwrite'); 
                var store=transaction.objectStore(storeName); 
                store.clear();
    }

2、调用数据库实例的deleteObjectStore方法可以删除一个object store。

This has to be called in onupgradened.

    if(db.objectStoreNames.contains('students')){ 
                        db.deleteObjectStore('students'); 
    }

8. Use of index

After adding an index, you can use the index to query data

The meaning of index is that it allows you to search any field, that is, get data records from any field. If you do not create an index, you can only search the primary key by default (that is, take values from the primary key).

Suppose that when you create a new table, the fields are indexed.

name

Create a new index. The three parameters of are the index name, the attribute where the index is located, and the configuration object (indicating whether the attribute contains duplicate values).

IDBObject.createIndex()
    objectStore.createIndex('name', 'name', { unique: false });

Now, you can find the corresponding data record from the.

name
    var transaction = db.transaction(['person'], 'readonly');
    var store = transaction.objectStore('person');
    var index = store.index('name');
    var request = index.get('李四');
    
    request.onsuccess = function (e) {
      var result = e.target.result;
      if (result) {
        // ...
      } else {
        // ...
      }
    }

9. Traversal data

To traverse all records of the data table, use the pointer object idbcursor.

Method is an asynchronous operation, so you should listen for events.

openCursor()
success

curson. Continue() moves the cursor down until no data returns undefined

index.openCursor()/``index.openKeyCursor()方法:在不传递参数的时候会获取object store所有记录
    function readAll() {
      var objectStore = db.transaction('person').objectStore('person');
    
         var request= objectStore.openCursor()
    
    
         request.onsuccess = function (event) {
         var cursor = event.target.result;
    
         if (cursor) {
           console.log('Id: ' + cursor.key);
           console.log('Name: ' + cursor.value.name);
           console.log('Age: ' + cursor.value.age);
           console.log('Email: ' + cursor.value.email);
           cursor.continue();
        } else {
          console.log('没有更多数据了!');
        }
      };
    }
    
    readAll();

Specify cursor range

You can use key range to limit the range of the value of the cursor and pass it as the first parameter to or

openCursor()
openKeyCursor()
  • IDBKeyRange.only(value):只获取指定数据
  • “`IDBKeyRange. Lower bound (value, is open): get the data with the minimum value. The second parameter is used to indicate whether to exclude the value itself, that is, whether it is an open interval in mathematics`
  • IDBKeyRange.upperBound(value,isOpen):和上面类似,用于获取最大值是value的数据
  • IDBKeyRange.bound(value1,value2,isOpen1,isOpen2):不用解释了吧

To get a student with an age of 26, you can use an index in conjunction with a cursor

    function getMultipleData(db,storeName){
                var transaction=db.transaction(storeName);
                var store=transaction.objectStore(storeName);
                var index = store.index("ageIndex");
                var request=index.openCursor(IDBKeyRange.only(26))
                request.onsuccess=function(e){
                    var cursor=e.target.result;
                    if(cursor){
                        var student=cursor.value;
                        console.log(student.id);
                        cursor.continue();
                    }
                }
            }

Get students whose initials are in B-E

    function getMultipleData(db,storeName){
                var transaction=db.transaction(storeName);
                var store=transaction.objectStore(storeName);
                var index = store.index("nameIndex");
                var request=index.openCursor(IDBKeyRange.bound('B','F',false,true));
                request.onsuccess=function(e){
                    var cursor=e.target.result;
                    if(cursor){
                        var student=cursor.value;
                        console.log(student.name);
                        cursor.continue();
                    }
                }
            }