IndexedDB: built-in database in the browser), built-in indexeddb

Source: Internet
Author: User

IndexedDB: built-in database in the browser (for conversion), built-in indexeddb

IndexedDB is a new built-in database in the browser in HTML5 specifications. You can use cookies or local storage to store data in a browser, but they are simple technologies. IndexedDB provides data storage and usage methods similar to the database style. Data stored in IndexedDB is permanently stored, and is not as temporary as cookies. IndexedDB provides the data query function, which can be used in online and offline modes. You can use IndexedDB to store large data.

Data in IndexedDB is stored as objects, and each object has a key value index. The operations in IndexedDB are transactional. An object is stored in an objectStore. objectStore is equivalent to a table in a relational database. IndexedDB can have many objectstores and many objects in objectStore. Each object can be obtained with a key value.

IndexedDB vs LocalStorage

Both IndexedDB and LocalStorage are used to store data in the browser, but they use different technologies and have different purposes. You need to select which one to use based on your own situation. LocalStorage stores data in key-value mode, but unlike IndexedDB, its data is not stored as objects. It stores all data in string format. If you want LocalStorage to store objects, you need to useJSON.stringify()The object can be converted into a string and reused.JSON.parse()Returns a string to an object. However, to store a large amount of complex data, this is not a good solution. After all, localstorage is designed specifically for a small amount of data, and its APIs are synchronized.

IndexedDB is suitable for storing a large amount of data. Its APIs are called asynchronously. IndexedDB uses indexes to store data, and various database operations are executed in transactions. IndexedDB even supports simple data types. IndexedDB is much more powerful than localstorage, but its APIs are also relatively complex.

For simple data, you should continue to use localstorage, but when you want to store a large amount of data, IndexedDB is obviously more suitable. IndexedDB can provide you with more complex data query methods.

IndexedDB vs Web SQL

WebSQL is also a technology for storing data in a browser. Unlike IndexedDB, IndexedDB is more like a NoSQL database, while WebSQL is more like a relational database and uses SQL to query data. W3C no longer supports this technology. For details, see http://www.w3.org/tr/webdatabase /.

Because it is no longer supported, you should not use this technology in the project.

IndexedDB vs Cookies

Cookies (small desserts) sound delicious, but they are not. Cookie data is transmitted every time an HTTP request is received or sent, which consumes additional traffic. For example, if you have a 10 KB cookie data and send 10 requests, a total of KB of data will be transmitted over the network. Cookies can only be strings. The storage space of Cookies in browsers is limited. Many users disable the use of Cookies in browsers. Therefore, Cookies can only be used to store a small amount of non-critical data.

IndexedDB usage

The best way to understand IndexedDB is to create a simple web application: store the student ID and name in IndexedDB. IndexedDB provides simple interfaces for adding, deleting, modifying, and querying data.

Open an IndexedDB Database

First, you need to know whether your browser supports IndexedDB. Please use the latest Google browser or Firefox browser. The earlier version of IE does not work.

Window. indexedDB = window. indexedDB | window. Indexes indexedDB | window. webkitIndexedDB | window. msIndexedDB; if (! Window. indexedDB) {console. log ("your browser does not support IndexedDB ");}

Once your browser supports IndexedDB, we can open it. You cannot directly open the IndexedDB database. IndexedDB requires you to create a request to open it.

 var request = window.indexedDB.open("testDB", 2);

The first parameter is the database name, and the second parameter is the database version number. The version number can be used to adjust the database structure and data when upgrading the database.

However, when you increase the database version numberonupgradeneededEvents, which may be successful, failed, or blocked.

Var db; request. onerror = function (event) {console. log ("failed to open DB", event);} request. onupgradeneeded = function (event) {console. log ("Upgrading"); db = event.tar get. result; var objectStore = db. createObjectStore ("students", {keyPath: "rollNo"}) ;}; request. onsuccess = function (event) {console. log ("successfully opened DB"); db = event.tar get. result ;}

onupgradeneededThe event will be called when the page is opened for the first time to initialize the database, or when the version number changes. Therefore, you shouldonupgradeneededFunction to create your stored data. If the version number does not change and the page has been opened before, you will getonsuccessEvent. Triggered when an error occurs.onerrorEvent. If you have not closed the connection before, it will triggeronblockedEvent.

In the code snippet above, we created an Object Store called "students" and used "rollNo" as the data key name.

Add objects to ObjectStore

To add data to the database, we first need to create a transaction and require read and write permissions. Any operations on accessing objects in indexedDB must be performed in transactions.

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.add({rollNo: rollNo, name: name});
Delete objects from ObjectStore

To delete an object, you need to create a transaction and call the delete interface to delete the object using the key.

db.transaction(["students"],"readwrite").objectStore("students").delete(rollNo);

It is easier to merge statements together, but the results are the same.

Retrieve objects using keys

Toget()Method to get the key value of the object.

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 must first extract it, 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 ("Updating:" + request. result. name + "to" + name); request. result. name = name; objectStore. put (request. result );};

All source code is here. If you have any questions, please leave a message or send me a private email via @

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.