Web Data persistent storage IndexedDB (not commonly used), webindexeddb

Source: Internet
Author: User

Web Data persistent storage IndexedDB (not commonly used), webindexeddb

IndexedDB is a type of database that stores structured data in a browser. It emerged to replace WebSQL (standards are obsolete but widely supported. IndexedDB uses NoSQL to operate databases. It stores and reads JavaScript objects and supports query and search.

The following are five parts:

1. Database Initialization

2. Object Storage space (ObjectStore)

3. Transactions

4. cursor Query

5. Index

Database Initialization

IndexedDB stores objects instead of tables. Open the database using the indexDB. open method. This method has two parameters: the first is the database name, and the second is the data version number.

PS: IndexedDB operations are completely asynchronous. For each IndexedDB operation, onerror or onsuccess event handler must be registered.

Var DB_NAME = 'Demo'; var DB_VERSION = 2; // use a positive integer. Do not use a floating-point var db; function initDb () {console. debug ("initDb... "); var req = indexedDB. open (DB_NAME, DB_VERSION); req. onsuccess = function (evt) {db = evt.tar get. result; console. debug ("initDb opened") ;}; req. onerror = function (evt) {console. error ("initDb error:", evt.tar get. errorCode | evt.tar get. error) ;}; // when the database version number is added, the onupgradeneeded event is triggered (called before onsuccess) req. onupgradeneeded = function (evt) {console. debug ("initDb. onupgradeneeded ");};}

PS: note that only the latest database version exists, and there are no databases of the same name in both versions.

Object Storage space (ObjectStore)

The object storage space (ObjectStore) can be imagined as a table in a relational database. When onupgradeneeded is triggered by the DB initialization, The ObjectStore is created. The createObjectStore method is used. The first parameter is the object name, and the second parameter is the object property. Generally, the keyPath is set as the key ).

Req. onupgradeneeded = function (evt) {console. debug ("initDb. onupgradeneeded "); var db = evt. currentTarget. result; // ObjectStore must be created in onupgradeneeded. Otherwise, var usersStore = db will fail to be created. createObjectStore ("users", {keyPath: "id "});};

The effect is as follows:

Transactions

All operations to read or modify data must be completed through transactions. Create a transaction using the transaction method. The first parameter is the ObjectStore to be accessed, and the second parameter is the access mode (readwrite, readonly, and read-only by default ).

Add data

Function addData () {var users = [{id: '001', name: 'Liu Yifei ', age: 18}, {id: '002', name: 'yang mi ', age: 19}]; var tx = db. transaction ("users", READ_WRITE); var store = tx. objectStore ("users"); var I = 0, len = users. length; while (I <len) {store. add (users [I ++]);}

Get Data

function getData(){     var tx = db.transaction("users");     var store = tx.objectStore("users");     var req = store.get("001");     req.onsuccess = function (evt) {          var res = evt.target.result;          console.debug(res);     };     req.onerror = function (evt) {          console.error("getData error:", evt.target.errorCode || evt.target.error);     };}

Modify data

Function updateData () {var tx = db. transaction ("users", READ_WRITE); var store = tx. objectStore ("users"); var req = store. put ({id: '001', name: 'Liu Yifei-Xiaolong female ', age: 18}); req. onsuccess = function (evt) {console. debug ("updateData success") ;}; req. onerror = function (evt) {console. error ("updateData error:", evt.tar get. errorCode | evt.tar get. error );};}

Delete data

function delData(){     var tx = db.transaction("users", READ_WRITE);     var store = tx.objectStore("users");     var req = store.delete("001");     req.onsuccess = function (evt) {          console.debug("delData success");     };     req.onerror = function (evt) {          console.error("delData error:", evt.target.errorCode || evt.target.error);     };} 

Clear Data

function clearData(){     var tx = db.transaction("users", READ_WRITE);     var store = tx.objectStore("users");     var req = store.clear();     req.onsuccess = function (evt) {          console.debug("clearData success");     };     req.onerror = function (evt) {          console.error("clearData error:", evt.target.errorCode || evt.target.error);     };}

Cursor Query

Transactions can be used to directly retrieve a single object through keys, and a cursor is required to retrieve multiple objects. A cursor is a pointer to a result set and results are not collected in advance. The cursor Pointer Points to the first item in the result. It points to the next item only when you receive the next command.

Function openCursor () {var tx = db. transaction ("users", READ_WRITE); var store = tx. objectStore ("users"); var req = store. openCursor (); req. onsuccess = function (evt) {var cursor = evt.tar get. result; if (cursor) {// check var value = cursor. value; console. log (value); if (value. name = 'yang mi ') {value. age = 16; cursor. update (value); // modify data (the read/write mode is required)} if (value. name = 'Liu Yan') {cursor. delete (); // delete the current entry} cursor. continue (); // move to the next item}; req. onerror = function (evt) {console. error ("openCursor error:", evt.tar get. errorCode | evt.tar get. error );};}

Note the following points:

1. to modify or delete data, you need to enable the read/write mode.

2. Non-empty check of cursor is necessary.

3. The onsuccess and onerror operations are also modified or deleted, but they are not written in the example.

4. Call continue to move to the next item.

In addition, you can set the key range and direction of the cursor, that is, when you open the openCursor method, you can pass these two parameters (openCursor (key range, direction). The first parameter is of the object type, the second parameter is of the string type.

Cursor key range

The key range is represented by the IDBKeyRange instance.

IDBKeyRange. only ('001'); // only the IDBKeyRange of the result with the key 001 is required. lowerBound ('002 '); // starts with the key 002 and ends with the last IDBKeyRange. lowerBound ('002 ', true); // starts with the key 002, but ignores 002 and ends with the last IDBKeyRange. upperBound ('002 '); // IDBKeyRange from the beginning to the end of the key 002. upperBound ('002 ', true); // starts from scratch until the key is 002, but the 002IDBKeyRange is ignored. bound ('001 ', '005'); // IDBKeyRange from 001 to 005. bound ('001 ', '005', true, true); // starts from 001 and ends to 005, but 001 and 005 are ignored.

Cursor direction

Next: From the first item to the last item (default)

Prev: from the last item to the first item

Index

When you need to use other attributes (non-primary keys) to obtain data, you must create an index in advance and then use the index to obtain data.

Create an index (when the database initializes the onupgradeneeded event)

The first parameter is the index name, the second parameter is the index attribute name, and the third parameter is an options object. Generally, unique is specified to set whether the index is unique.

usersStore.createIndex("name", "name", { unique : false });

Index data acquisition

Function indexGetData () {var tx = db. transaction ("users", READ_WRITE); var store = tx. objectStore ("users"); var index = store. index ("name"); var req = index. get ("Yang Mi") req. onsuccess = function (evt) {console. debug ("indexGet success", evt.tar get. result) ;}; req. onerror = function (evt) {console. error ("indexGet error:", evt.tar get. errorCode | evt.tar get. error) ;};} function indexOpenCursor () {var tx = db. transaction ("users", READ_WRITE); var store = tx. objectStore ("users"); var index = store. index ("name"); var req = index. openCursor (); req. onsuccess = function (evt) {var cursor = evt.tar get. result; if (cursor) {// check var value = cursor. value; console. log (value); cursor. continue (); // move to the next item}; req. onerror = function (evt) {console. error ("openCursor error:", evt.tar get. errorCode | evt.tar get. error );};}

PS: The index usage is the same as the normal value and the cursor value.

All indexes of OSS

function indexNames(){     var tx = db.transaction("users", READ_WRITE);    var store = tx.objectStore("users");     var indexNames = store.indexNames;     var index, i = 0, len = indexNames.length;     while(i < len){          index = store.index(indexNames[i++]);          console.log(index);     }}

Browser support

PS: Chart source> http://caniuse.com/#feat=indexeddb

Summary

When IndexedDB is used, someone may compare it with WebSQL and find that IndexedDB cannot be used for table join (because it does not exist at all), that is, to find a data, the score may be scored several times.

For example, if you want to obtain the course scores of a student from three tables: Student, course, and score, you have to connect the three tables. However, if you use IndexedDB, you can get the score three times, take out the student first, take out the course, and then get the score.

It seems that IndexedDB is stupid, so it becomes a misunderstanding. Why do you need to store the data you want to display so that NoSql uses NoSql to store student scores directly as an object, one query is enough.

Example download: http://files.cnblogs.com/files/lovesong/IndexedDBdemo.zip

 

This article is an original article. If you repost it, please keep the original source for tracing convenience. If there is any error, thank you for your correction.

Address: http://www.cnblogs.com/lovesong/p/5055384.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.