INDEXEDDB of front-end storage

Source: Internet
Author: User
Tags createindex data structures

Tag: PAC string field name array error Error listening message ReadWrite

In the previous phase of the work, the project team to develop a platform, in order to make a better user experience, requires a front-end separation, so this is the front-end implementation of storage, then I went to the next most Popular front-end storage database, found the INDEXEDDB, So he did a more in-depth exploration of INDEXEDDB, this article is to record the exploration process of some experience.

What is INDEXEDDB?

Before using a technology to understand what it is, this is important to your understanding, from the DB can be seen, it is certainly a database, and when it comes to the database, there are two different types of databases, relational database and non-relational database, relational database such as MySQL, Oracle stores data in tables, and non-relational databases such as Redis, MongoDB, and so on, store the dataset as an individual object. INDEXEDDB is a non-relational database that does not require you to write specific SQL statements to manipulate the database because it is nosql and uses JSON in the form of data.

The significance of INDEXEDDB appearance

Perhaps familiarity with the front-end storage would say, is there localstorage and cookies? Why do we have to launch INDEXEDDB? In fact, you can use cookies or local storage to store data in a browser, but they are relatively simple techniques, and INDEXEDDB provides data storage and usage in a database-like fashion.

First of all, to say that cookies, English direct translation is a small dessert, it sounds delicious, in fact, it is not, each HTTP receive and send will pass the cookie data, it will occupy additional traffic. For example, if you have a 10KB cookie data that sends 10 requests, then a total of 100KB of data will be transmitted over the network. Cookies can only be strings. There is limited space in the browser to store cookies, and many users prohibit cookies from being used by browsers. Therefore, cookies can only be used to store a small amount of non-critical data.

Second, Localstorage,localstorage is storing data in Key-value key-value mode, but unlike INDEXEDDB, its data is not stored as objects. The data it stores is in string form. If you want Localstorage to store objects, you need to use json.stringify () to turn the object into a string, and then use Json.parse () to restore the string to an object. But if you want to store a lot of complex data, this is not a good solution. After all, Localstorage is specifically designed for small amounts of data, so its API is designed to be synchronous. INDEXEDDB is ideal for storing large amounts of data, and its APIs are called asynchronously. INDEXEDDB uses indexes to store data, and various database operations are performed in a transaction. 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 localstorage, but when you want to store large amounts of data, INDEXEDDB will be significantly more appropriate, INDEXEDDB can provide you with more complex ways to query data.

Characteristics of INDEXEDDB

1. Object Warehouse

After having a database we naturally want to create a table to store the data, but INDEXEDDB does not have the concept of a table, but ObjectStore, a database can contain multiple objectstore,objectstore is a flexible data structure, You can store multiple types of data. In other words, a objectstore is equivalent to a table, and each piece of data stored in it is associated with a single key. We can use one of the specified fields in each record as the key value (KeyPath), or we can use the auto-generated increment number as the key value (Keygenerator), or we can not specify it. There are differences in the data structures that ObjectStore can store, depending on the type of selection key.

key type

store data

Do not use

Any value, but need to specify key parameters when no data is added

KeyPath

Any value, But you do not have to add a piece of data when you need to specify a key parameter

keygenerator

Any value

Both use

JavaScript object, if there is keypath specified property in the object does not generate a new key value, if not automatically generated increment key value, Padding KeyPath specifying properties

For example, there is an object store that holds the person, which is the ID value of the person.

2. Transactional

In Indexeddb, each operation on a database is performed in the context of a transaction. A transaction scope affects one or more object stores at a time, and you define it by passing in an array of object store names to the function that creates the transaction scope. For example: Db.transaction (storeName, ' ReadWrite '), the second parameter for creating a transaction is the transaction pattern. When you request a transaction, you must decide whether to request access in read-only or read-write mode.

3. Request-based

Each operation on the INDEXEDDB database is described as opening the database through a request, accessing an object store, and then continuing. The IndexedDB API is inherently request-based, which is also an API asynchronous nature indicator. For each operation you perform in the database, you must first create a request for this operation. When the request is complete, you can respond to events and errors generated by the request result.

4. Asynchronous

In INDEXEDDB most operations are not our usual method of calling, returning the result of the pattern, but the request-response mode, the so-called asynchronous API is not the execution of this command is complete, We can use the Request.result to get the Indexeddb object, just like using AJAX, the statement does not mean that the object has been acquired, so we generally handle it in its callback function.

Indexeddb How to Play

The basic pattern that IndexedDB encourages to use is as follows:

    1. Open the database and start a transaction.
    2. Create an object store.
    3. Build a request to perform some database operations, such as adding or extracting data.
    4. Wait for the operation to complete by listening for the correct type of DOM event.
    5. Take some action on the result of the operation (can be found in the request object)

Next, if you want to understand indexeddb how to play, the best way is to create a simple Web application: The name of the person, phone, address stored in the INDEXEDDB. INDEXEDDB provides a simple add, delete, change, check interface, the interface is as follows:

1. Open the Database

A) First, you need to know if your browser supports INDEXEDDB.

var indexedDB = Window.indexeddb | | WINDOW.WEBKITINDEXEDDB | | WINDOW.MOZINDEXEDDB | | Window.msindexeddb; if (! IndexedDB) {    Console.log ("Your browser does not support INDEXEDDB");}

b) Create request Open INDEXEDDB: Once your browser supports INDEXEDDB, we can open it. You cannot open the INDEXEDDB database directly. INDEXEDDB needs you to create a request to open it.

var request = Indexeddb.open (name, version);

The first parameter is the name of the database, and the second parameter is the version number of the database. The version number can be used to adjust the database structure and data when the database is upgraded. However, when you increase the database version number, the Onupgradeneeded event is triggered, and there are three scenarios in which success, failure, and blocking events can occur:

Request.onerror =function(e) {console.log (e.currenttarget.error.message);    }; Request.onsuccess=function(e) {mydb.db=E.target.result; Console.log (' Successfully opened DB ');    }; request.onupgradeneeded=function(e) {vardb =E.target.result; if(!db.objectstorenames.contains (' person ')) {Console.log ("I need to create a new storage object"); //If the table does not exist, create a new table (KeyPath, primary key; AutoIncrement, whether self-increment), return an object (ObjectStore)            varObjectStore = Db.createobjectstore (' person ', {keypath:"id", AutoIncrement:true            }); //specify the fields that can be indexed, unique fieldsObjectstore.createindex ("Name", "name", {unique:false            }); Objectstore.createindex ("Phone", "phone", {unique:false            }); } console.log (' Database version changed to: ' +version);};

The onupgradeneeded event is called when the first time the page is opened to initialize the database, or when there is a change in the version number. So, you should create your stored data in the onupgradeneeded function. If there is no change in the version number and the page has been opened before, you will get a onsuccess event.

2. Add Data

A) You first need to create a transaction and require read and write permissions

var transaction = db.transaction (StoreName, ' readwrite ');

b) Get ObjectStore, and then call the Add method to add the data

var store = Transaction.objectstore (storeName);     var request = store.get (key);     function (e) {        = e.target.result;        Console.log (student.name);};

3. Delete data

Delete as new, you need to create a transaction, and then call the delete interface, delete the object by key.

var transaction = db.transaction (StoreName, ' ReadWrite ');     var store = Transaction.objectstore (storeName), store. Delete (key);

4. Finding data

A) Search by key

Open the transaction, get the ObjectStore, call the Get () method, pass the object's key value into the method, and remove the corresponding object

var transaction = db.transaction (StoreName, ' ReadWrite ');     var store = Transaction.objectstore (storeName);     var request = store.get (key);     function (e) {        = e.target.result;        Console.log (student.name);};

b) Use index Lookup

We can specify the index when creating the object store, using the CreateIndex of the object store to create an index with three parameters: index name, indexed attribute field name, and index attribute value unique.

Objectstore.createindex ("name", "name", {                false            });

As in the code above, we've built the name index, and we can use that index to query:

var transaction = db.transaction (storeName);     var store = Transaction.objectstore (storeName);     var index = store.index (search_index);     function (e) {        = e.target.result;        Console.log (student.id);}

c) CURSOR Traversal data

The students who are familiar with the database have a good understanding of the role of cursors, with the database object store cursor, we can use the cursor to traverse the object store.

varTransaction =db.transaction (storeName); varstore =Transaction.objectstore (storeName); varRequest = Store.opencursor ();//Open Cursor    varDataList =NewArray (); vari = 0; Request.onsuccess=function(e) {varcursor =E.target.result; if(cursor) {console.log (Cursor.key); Datalist[i]=Cursor.value;            Console.log (Datalist[i].name); I++; Cursor.Continue(); } Data=dataList;};

4. Updating objects

To update an object, first take it out, modify it, and then put it back.

 var  transaction = db.transaction (StoreName, ' readwrite ' 

5. Close and delete a database

Closing a database can call the Close method of a database object directly

function closedb (db) {    db.close ();}

Delete a database DeleteDatabase method using a Database object

function Deletedb (name) {    indexeddb.deletedatabase (name);}
Summarize

The above is indexeddb some basic concepts and use, due to space reasons, there are some more powerful features not introduced, in fact, INDEXEDDB cursors combined with the index to play a real power, interested in the small partners can continue in-depth research, there is to pay attention to browser support issues, IE9 and earlier versions do not support, Firefox and Google browser is not a problem, recommended use, if the article is flawed or insufficient, please correct ~

INDEXEDDB of front-end storage

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.