HTML5 Local Storage--indexeddb (one: basic use)

Source: Internet
Author: User

In HTML5 local storage--web SQL database mentions that the WEB SQL database has actually been deprecated, while HTML5 's supported local storage actually becomes

Web Storage (local Storage and session Storage) and INDEXEDDB. Web storage uses simple string key value pairs to store data locally, but for a large number of structured data stores, INDEXEDDB is designed to store large amounts of structured data on the client side and use indexed efficiently retrieved APIs. Asynchronous API

Most operations in INDEXEDDB are not our usual invocation methods, returning the pattern of the result, but rather the request-response pattern, such as the operation to open the database

var request=window.indexeddb.open (' TestDB ');

This instruction does not return a handle to a DB object, we get a Idbopendbrequest object, and the DB object we want to get is in its result property,

The response of this instruction request is a Idbdatabase object, which is the Indexeddb object,

In addition to the Result,idbopendbrequest interface defines several important attributes OnError: Request failed callback function handle onsuccess: Request successful callback function handle onupgradeneeded: Request database version change handle

The asynchronous API is not that this instruction is executed, we can use Request.result to get the Indexeddb object, just as using Ajax, the execution of the statement does not mean that the object has been acquired, so we typically handle it in its callback function. Creating a database

Just now the statement has shown how to open a INDEXEDDB database, call the Indexeddb.open method to create or open a indexeddb. Look at a complete deal

function Opendb (name) {
            var request=window.indexeddb.open (name);
            Request.onerror=function (e) {
                console.log (' OPen error! ');
            };
            Request.onsuccess=function (e) {
                mydb.db=e.target.result;}
            ;
        }

        var mydb={
            name: ' Test ',
            version:1,
            db:null
        };
        OPENDB (Mydb.name);

A MyDB object is defined in the code that assigns the DB object obtained by the request to the DB property of the MyDB in the successful destroy function of creating the INDEXEDDB request, so that mydb.db can be used to access the INDEXEDDB created. version

We note that there is a similar callback function handle--onupgradeneeded in addition to OnError and Onsuccess,idbopendbrequest. This handle is invoked when we request that the version number of the Open database is inconsistent with the existing database version number.

The Indexeddb.open () method also has a second optional parameter, the database version number, the default version number 1 when the database is created, and the onupgradeneeded is invoked when our incoming version number is inconsistent with the current version number of the database. Of course we can't try to open version that is lower than the current database edition, otherwise the call is onerror, modify just the example

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);
            }

        var mydb={
            name: ' Test ',
            Version:3,
            db:null
        };
        OPENDB (mydb.name,mydb.version);

Since a version 1 database has just been created, a version of 3 will be turned on in the console output: DB version changed to 3 closing and deleting the database

Close the database object can be called directly by closing the method

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

Deleting a database using the DeleteDatabase method of the Indexeddb object

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

Simple call

var mydb={
            name: ' Test ',
            Version:3,
            db:null
        };
        OPENDB (mydb.name,mydb.version);
        settimeout (function () {
            closedb (mydb.db);
            Deletedb (mydb.name);
        },500);

Because the asynchronous API is willing to make it impossible to get a DB object before the Closedb method call (actually getting the DB object is much slower than executing a statement), the settimeout is delayed. Of course, we notice that each INDEXEDDB instance has onclose callback function handle, the database is closed when processing, interested students can try, the principle is very simple, not demonstrated.

Object Store

With the 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, Multiple types of data can be stored. That is, a objectstore is equivalent to a table in which each piece of data stored is associated with a key.

We can use one of the specified fields in each record as the key value (KeyPath), or you can use an automatically generated increment number as the key value (Keygenerator), or you can not specify it. Different types of key choices, ObjectStore can store data structures differently

Key type Storing data
Do not use Any value, but you need to specify key parameters without adding a single piece of data
KeyPath JavaScript object, the object must have a property as a key value
Keygenerator Any value
are used A JavaScript object that does not generate a new key value if there is a KeyPath specified property in the object, and if the increment key value is not automatically generated, the fill keypath the specified property

Affairs

Before you do anything about a new database, you need to start a transaction. In a transaction, you need to specify which object store the transaction spans.

Transaction has three modes read only: Read, cannot modify database data, can execute concurrently read and write: ReadWrite, can be read-write operation version change: Verionchange

var transaction=db.transaction ([Students ', ' taecher ']);  Open a transaction using the students and teacher object store
var objectstore=transaction.objectstore (' students ');//Get Students Object Store
add data to object store

The Createobjectstore method that invokes the database instance can create the object store with two parameters: Store name and key type. Call the store's Add method to add data. With the above knowledge, we can add data to the object store.

KeyPath

Because operations on new data need to be done in transaction, and transaction requires the object store to be specified, we can only initialize the object store for later use when we create the database. This is one of the important roles of onupgradeneeded, modifying the previous code

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) {
                var db=e.target.result;
                if (!db.objectstorenames.contains (' students ')) {
                    db.createobjectstore (' students ', {keypath: ' id '});
                }
                Console.log (' DB version changed to ' +version);}
        

So when we create the database, we add an object store called students to prepare some data for adding

var students=[{ 
            id:1001, 
            name: "Byron", 
            age:24 
        },{id:1002 
            , 
            name: "Frank", 
            age:30 
        },{ 
            id:1003, 
            name: "Aaron", 
            age:26 
        }];
function AddData (db,storename) {
            var transaction=db.transaction (storename, ' readwrite '); 
            var store=transaction.objectstore (storename); 

            for (Var i=0;i<students.length;i++) {
                store.add (students[i]);
            }


OPENDB (mydb.name,mydb.version);
        settimeout (function () {
            addData (mydb.db, ' students ');
        },1000);

So we've added three records to the students object store, with the ID key, to see the effect on the Chrome console.

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.