HTML5 new Feature client database (IndexedDB)

Source: Internet
Author: User

1. Brief introduction

In HTML5 local storage--web SQL database mentions that Web SQL database has actually been deprecated (since Firefox and IE are not supported by now), and HTML5 's supported local storage has actually become a web Storage Storage and Session Storage) and INDEXEDDB. Web storage uses simple string key-value pairs to store data locally for ease of use, but for a large number of structured data stores, INDEXEDDB is designed to be able to store large amounts of structured data on the client side and use an index to efficiently retrieve the API.

2. Basic Features

(1). INDEXEDDB is an object database, or NoSQL (not justSQL), which is much simpler than a database that supports SQL queries, but is more powerful, more efficient, and more robust than the key/value pairs supported by the Web Storage API.

(2). INDEXEDDB like Web Storage and file system APIs, the INDEXEDDB database is also limited by the same-origin policy (that is, cross-domain issues ), meaning that two of the same-origin Web pages can access each other's data, but non-homologous pages cannot be accessed.

(3). Each source of the INDEXEDDB can have any number of INDEXEDDB databases. But the name of each database must be unique under that source, and in the Indexdb API, a database is actually a collection of named object storage intervals (objects store).

(4). Introduction to NoSQL:

NoSQL (NoSQL = not-only sql), meaning "not just sql."
On modern computing systems, a huge amount of data is generated every day on the network.
A significant portion of this data is handled by the relational database management system (RDMBSS). 1970 E.f.codd's paper "A Relational model of data

For large shared data banks ",

This makes data modeling and application programming easier.
The application proves that the relational model is well suited to client server programming, far exceeding the expected benefits, and today it is the leading technology for structured data storage in network and business applications.
NoSQL is a new revolutionary movement in the database, and early on, there was a growing trend in the 2009. NoSQL advocates are advocating the use of non-relational data storage,

Compared with the overwhelming use of relational database, this concept is undoubtedly a new kind of thinking injection.

(5). relational databases Follow acid rules

5-1:a (atomicity) atomicity
Atomicity is easy to understand, that is, all operations in a transaction are either done or not, and the transaction succeeds because all operations in the transaction are successful, and as long as one operation fails, the entire transaction fails and needs to be rolled back.
For example, bank transfer, transfer from a account 100 to B account, divided into two steps: 1) from a account 100 yuan, 2) deposited into the account of 100 to B. The two steps are either completed together, or not completed together, if only the first step, the second step fails, the money will be inexplicably less than 100 yuan.
5-2:C (consistency) consistency
Consistency is also relatively easy to understand, that is, the database should always be in a consistent state, the operation of the transaction will not change the original consistency of the database constraints.
For example, if an existing integrity constraint a+b=10, if a transaction changes A, then the B must be changed so that the transaction will still satisfy a+b=10, otherwise the transaction fails.
5-3:i (isolation) Independence
The so-called independence refers to the concurrent transactions do not affect each other, if one transaction to access the data is being modified by another transaction, as long as another transaction is not committed, the data it accesses is not affected by uncommitted transactions.
For example, there is a transaction from a to 100 yuan to the B account, in the case of the transaction is not completed, if at this time B query their own account, is not see the new increase of 100 yuan.
5-4.D (Durability) Persistence
Persistence means that once a transaction commits, its modifications are persisted to the database, even if the outage occurs.

3. Asynchronous API use:

Most operations in INDEXEDDB are not our usual method of calling, returning the result of the pattern, but the request-response pattern, such as opening the database operation:

var request=window.indexeddb.open (' TestDB ');
This instruction does not return a handle to a DB object, we get a Idbopendbrequest object, and we want to get the DB object in its Result property:

The response requested by this instruction is a Idbdatabase object, which is the Indexeddb object:

In addition to the Result,idbopendbrequest interface, several important attributes are defined:
onerror: Request failed callback function handle

onsuccess: callback function handle for successful request

onupgradeneeded: Request database version change handle

The so-called asynchronous API is not the execution of this instruction, we can use Request.result to get the Indexeddb object, just like using AJAX, the statement does not mean that the object has been obtained,

So we usually deal with it in its callback function.

4. Create a Database

Just now the statement has shown how to open a INDEXEDDB database and call the Indexeddb.open method to create or open a indexeddb. See 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);
5.version

We have noticed that in addition to onerror and Onsuccess,idbopendbrequest there is a similar callback function handle--onupgradeneeded. This handle is in the version number of the database that we requested to open

is called when there is an inconsistency with the existing database version number.

The Indexeddb.open () method also has a second optional parameter, the database version number, the default version number is 1 when the database is created, and when the version number that we passed is inconsistent with the current version number of the database

Onupgradeneeded will be called, of course, we can not try to open a version that is lower than the current database, 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 database of version 1 has just been created and opened at 3, the console output will be: DB version changed to 3


5. Close and delete a database

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

function Closedb (db) {            db.close ();        }
To delete a database using the Indexeddb object's DeleteDatabase method:

function Deletedb (name) {            indexeddb.deletedatabase (name);        }
Simple to use:

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, it is not guaranteed to get the DB object before the Closedb method call (actually getting the DB object is much slower than executing a statement).

So I used the settimeout delay a bit. Of course we notice that each INDEXEDDB instance has a OnClose callback function handle, which is handled when the database is closed,

Interested students can try, the principle is very simple, do not demonstrate.

6.object Store

With the database we naturally want to create a table to store the data, but there is no concept of tables in INDEXEDDB, but ObjectStore, a database can contain multiple objectstore,

ObjectStore is a flexible data structure that 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 Storage type
Do not use Any value, but you need to specify a key parameter when you don't add 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 the object has KeyPath specified property, and if the increment key value is not automatically generated, the fill keypath the specified property


7. Transaction:

Before you do anything for the new database, you need to start a transaction. The transaction needs to specify which object store the transaction spans.

There are three modes of transactions

1. Read only: Read, cannot modify database data, can execute concurrently
2. Read and write: ReadWrite, can be read and write operation
3. Version change: Verionchange

var transaction=db.transaction ([' Students ', ' taecher ']);  Open a transaction, using students and teacher object Storevar objectstore=transaction.objectstore (' Students '); Get Students Object Store

8. Adding data to the object store

Call the Createobjectstore method of the DB instance to create an object store with two parameters: the store name and the key type. Add data by calling the store's Add method.

With this knowledge, we can add data to the object store.

KeyPath:

Because the operation of the new data needs to be done in transaction, and transaction is required to specify the object store, we can only initialize the database when we create it.

Object store for later use, which is an important part 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 created the database, we added an object store named 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 added three records in the students object store, with the ID key, to see the effect in the Chrome console:



9. Finding data

You can call the Get method of the object store to get the data by key, using KeyPath as an example:

function Getdatabykey (db,storename,value) {            var transaction=db.transaction (storeName, ' readwrite ');             var store=transaction.objectstore (storeName);             var request=store.get (value);             Request.onsuccess=function (e) {                 var student=e.target.result;                 Console.log (student.name);}             ;}
10. Updating data

You can call the Put method of the object store to update the data and automatically replace the record with the same key value for the update purpose, without the same add, to use KeyPath as an example

function Updatedatabykey (db,storename,value) {            var transaction=db.transaction (storeName, ' readwrite ');             var store=transaction.objectstore (storeName);             var request=store.get (value);             Request.onsuccess=function (e) {                 var student=e.target.result;                 student.age=35;                Store.put (student);}             ;}
11. Delete Data and Object store

Call the Delete method of the object store to delete records based on key values

function Deletedatabykey (db,storename,value) {            var transaction=db.transaction (storeName, ' readwrite ');             var store=transaction.objectstore (storeName);             Store.delete (value);         }
You can empty the object store by calling the clear method of the object store

function Clearobjectstore (db,storename) {            var transaction=db.transaction (storeName, ' readwrite ');             var store=transaction.objectstore (storeName);             Store.clear ();}
The Deleteobjectstore method that invokes the DB instance can delete an object store, which is called in the onupgradeneeded.

if (db.objectStoreNames.contains (' students ')) {                     db.deleteobjectstore (' Students ');}
At last:

This is about the basic use of indexeddb, a lot of students will feel very chicken, and our normal own definition of the object use no difference, that is, can be saved in the local, this is because we have not introduced indexeddb known as the indexed of the Killing device-index, This is what let indexeddb prowess, next we will look at this kill device.


HTML5 new Feature client database (IndexedDB)

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.