IndexedDB: Database built into the browser (go)

Source: Internet
Author: User

INDEXEDDB is the database built into the newly emerged browser in the HTML5 specification. For storing data in a browser, you can use cookies or local storage, but they are relatively simple techniques, and INDEXEDDB provides data storage and usage in a database-like fashion. The data stored in the INDEXEDDB is permanently stored, unlike cookies, which are only temporary. The INDEXEDDB provides the ability to query data in both online and offline modes. You can store large data with INDEXEDDB.

INDEXEDDB data is stored as an object, and each object has a key value index. The operations in the INDEXEDDB are transactional. An object is stored in a objectstore, and ObjectStore is equivalent to a table in a relational database. INDEXEDDB can have a lot of objects in Objectstore,objectstore. Each object can be obtained with a key value.

IndexedDB vs Localstorage

INDEXEDDB and Localstorage are used to store data in a browser, but they use different techniques and have different uses, and you need to choose which ones to use according to your own circumstances. Localstorage stores data in Key-value key-value mode, but unlike INDEXEDDB, its data is not stored as an object. The data it stores is in string form. If you want Localstorage to store objects, you need to be JSON.stringify() able to turn the object into a string, and then JSON.parse() 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 designed for small amounts of data, and its APIs are 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.

IndexedDB vs Web SQL

Websql is also a technique for storing data in a browser, unlike INDEXEDDB, where INDEXEDDB is more like a NoSQL database, and Websql is more like a relational database, using SQL to query data. The technology is no longer supported by the consortium. For details, see: http://www.w3.org/TR/webdatabase/.

Because it is no longer supported, you should not use this technique in your project.

IndexedDB vs Cookies

Cookies (small desserts) sound delicious, but in fact they are not. Each HTTP receive and send will pass the cookie data, which consumes 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.

The use of INDEXEDDB

The best way to understand INDEXEDDB is to create a simple Web application that stores the student's school number and name in INDEXEDDB. INDEXEDDB provides a simple add, delete, change, check interface.

Open a INDEXEDDB database

First, you need to know if your browser supports INDEXEDDB. Please use the latest version of Google Chrome or Firefox browser. The low version of IE is not possible.

Window. IndexedDB= window.indexeddb | | Window.mozindexeddb | | Window.webkitindexeddb | | window.msindexeddb if (!window.indexeddb{consolelog ( "Your browser does not support 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.

= Window. IndexedDB.  Open("TestDB"2);       

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, onupgradeneeded events are triggered, and there are three scenarios in which success, failure, and blocking events can occur.

var db; request. onerror=function(Event){Console.Log("Failed to open DB", event);}request. onupgradeneeded=function(Event){Console.Log("Upgrading"); Db= Event. Target. Result;var ObjectStore= db.Createobjectstore("Students",{KeyPath: "Rollno" }) };request= function ( Event{console . log (= Event.target.result;}               

onupgradeneededEvents are called when the first page is opened to initialize the database, or when there is a change in the version number. So, you should onupgradeneeded create your stored data in a function. If there is no change in the version number and the page has been opened before, you will get an onsuccess event. The event is triggered if an error occurs onerror . If you did not close the connection before, the event will be triggered onblocked .

In the code snippet above, we created an object Store called "Students", with "Rollno" as the Data key name.

Add Objects to ObjectStore

In order to add data to the database, we first need to create a transaction and ask for Read and write permissions. The operation of any Access object in the INDEXEDDB needs to be performed in the transaction.

VAR transaction= db.Transaction(["Students"],"ReadWrite"); transaction. oncomplete=function(Event){Console.Log("Success");}; transaction. onerror=function(Event){Console.Log( "Error" ) ;}var objectstore = transaction objectstore ( "students" ;objectstore.< Span class= "token function" >add ({rollno: Rollno: name< Span class= "token punctuation" >}    
deleting objects from ObjectStore

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

DB.  Transaction(["Students"],"ReadWrite").  ObjectStore("Students").  Delete(Rollno);                

I merge the statements together to make it simpler, but the effect is the same.

Remove objects with key

The get() key value of the object is passed into the method, and the corresponding object is removed.

var request= db.Transaction(["Students"],"ReadWrite").ObjectStore("Students"). Get(Rollno); request. onsuccess = function(event){console.  Log("Name:"+request. Result. Name); }; 
Update an Object

To update an object, you first need to 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(+request.name +  "to" + name.result.name = Name; Objectstore. Put.result ;}  
All the source code is here. If you have any questions, please leave a message, or pass the  @ to me.

IndexedDB: Database built into the browser (go)

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.