HTML5 INDEXEDDB front-end local storage DB Instance tutorial (reprint)

Source: Internet
Author: User
Tags comparison table createindex sqlite ticket

First, why did INDEXEDDB replace the web SQL Database?

With the children's education has never been a "win at the starting line" this way, in the front-end area, is not where to first come out of which in the future to lead the coquettish.

HTML5 indexeddb and Web SQL database are local database data stores, and web SQL databases are going to come out earlier, and then eggs. The Web SQL database was doomed to be a dead start on November 18, 2010, when the Web was announced to abandon the text.

The future must be indexeddb, from the current browser compatibility point of view, it also shows this result:

You can see that IE and Firefox do not support the Web SQL Database, basically can be concluded that will never support, specifications are not recognized, there is no waste of energy to support the reasons.

Okay, now we know. INDEXEDDB instead of Web SQL database is set, so do you know why Web SQL database is discarded?

Here is a web SQL database code:

Database.transaction (Function (TX) {    tx.executesql ("CREATE TABLE IF not EXISTS tasks (ID REAL UNIQUE, text text)", []); }

Can see directly to the SQL statement to JS, the mainstream relational database is the sense of vision, so the design seems to be understandable, but precisely this design has become a Web SQL database is discarded one of the important reasons: first, the study cost is much higher, although the SQL itself is not complex, but the span is large, For example, the Division I Play JS engineers and the engineer playing SQL also separated by a play PHP engineer; The second is the use of itself is inconvenient, need to convert the JS object into a relational string statement, very verbose.

and Indexeddb direct JS object storage, seamless docking.

The following table provides a more detailed comparison of INDEXEDDB and Web SQL database content:

websql IndexedDB
Advantages The real relational database, like SQLite (SQLite is a lightweight relational database management system that adheres to acid)
  • Allows fast indexing and searching of objects, so in a Web application scenario, you can manage data very quickly and read/write data.
  • Because it is a NoSQL database, we can set our JavaScript objects and indexes according to our actual needs.
  • Working in asynchronous mode, each transaction has a moderately granular lock. This allows you to work within JavaScript's event-driven modules.
Insufficient
  • The spec doesn't support it.
  • Because of the use of the SQL language, we need to master and transform our JavaScript objects into corresponding query statements.
  • Non-object driven.
If you have a relational database in your worldview, it's probably not easy to understand.
Position A table that contains rows and columns. A storage object that contains JavaScript objects and keys.
Query mechanism Sql Cursor Apis,key Range APIs, application code
Transaction Locks can occur in databases, tables, rows of "read and write" times. Locks can occur in database version change transactions, or when storage objects are "read-only" and "read-write" transactions.
Transaction commit Transaction creation is explicit. The default is rollback unless we invoke commit. Transaction creation is explicit. The default is to commit unless we call abort or there is an error not being captured.

stop!

Can not continue to say, estimated to read the above comparison table in the content, already have a lot of students already some do not know why, because it involves a lot of database related concepts, want to easily understand the above content and more easily grasp the relevant knowledge of INDEXEDDB, these concepts still need to master.

Second, you must first understand some concepts of the database

For the front-end students, the database concept is not necessary to understand the very precise, just need to know how to go about it, so, some of the following explanations will be their intention, do not chew the word.

1. Relational database and non-relational database

"Relational database" is a long history, has half a century, occupy the mainstream of the database model, it is estimated that most of your company's Web site is the use of this database model. The "non-relational database" (NoSQL database) is much younger, according to the data shown by Carlo Strozzi in 1998, 20 years, using key-value pairs to store data, and the structure is not fixed, very similar to the pure object in JavaScript.

var obj = {  key1: ' value1 ',  key2: ' value2 ',  key3: ' Value3 ',  ...};

The relational database is very strict with conformance requirements, such as writing 100 data, the first 99 succeeded, and the 100th is illegal, and the transaction is rolled back to its original state. This guarantees that the stored data is in a consistent state at the end of the transaction and at the beginning. Ideal for banks that require very high data consistency scenarios. However, this consistency guarantee is sacrificing part of the performance.

However, for Weibo, QQ space this kind of web2.0 application, consistency is not so important, for example, friend A to see my homepage and friends B to see my homepage information has different, no big deal, there is a few seconds difference is OK. While this type of application is less consistent, it has a high performance requirement because it is too frequent to read and write. If you use a "relational database", the benefits of consistency do not yield much, but the performance problem is more obvious, at this time, do not guarantee consistency but better performance of the "non-relational database" is more appropriate. At the same time, because the data structure of "non-relational database" is not fixed, it is easy to expand. Because of the social networking site, demand changes that is a day three meals often, add new field is unavoidable, "non-relational database" easy to go, if the use of "relational database", most of the data changes, we must carefully pondering.

From the temperament, "relational database" stable and long-term, "non-relational database" quickly smart.

In the front-end domain, the Web SQL database is "relational" and Indexeddb is a "non-relational database".

2. Understand transaction-transaction in the database

The transaction of the database (in English as ' transaction '), we can understand the operation of the database, but also refers to a sequence of operations. For example, bank transfer, one account has less money and then another account has more money, both of which are either executed or not executed. Such operations can be seen as a transaction.

The main purpose of the transaction is to ensure consistency of data in concurrency. Transactions in a relational database have the following 4 basic characteristics:

    1. Atomicity (atomicity): All operations in a transaction are committed or rolled back as a whole.
    2. Consistency (CONSISTEMCY): When things are done, the data must be consistent to ensure that the data is lossless.
    3. Isolation (Isolation): Multiple transactions that modify data are isolated from each other.
    4. Persistence (Durability): After a transaction completes, its effect on the system is permanent, and the modification persists even if a system failure occurs.

The first letter of these 4 basic features is usually extracted from the professional description, collectively referred to as "acid Properties ". The transaction execution process can be superficially understood as: Start transaction, Balabala operation, if error, rollback (rollback), if no problem, commit (commit), end transaction.

3. Understanding cursors in the database-cursor

The common thing associated with "cursors" in the real world is the "vernier caliper", which has a range of ticks:

Cursors in the database actually have something in common with them. The memory bar is essentially like a ruler, and we can imagine that there are many ticks on it, and then the memory size is stacked up by one of these ticks. Database transactions in order to ensure that data can be rolled back, it is clear that there is a memory area to place those that are about to be affected is the data, this memory area of the virtual table is the database "cursor".

And the real world "vernier caliper" mapping is: A tick represents a row of data, the cursor is a ruler on a piece of the area, want to get a row of data in the database, we can traverse this cursor.

4. "Lock"-lock in the database

The "lock" in the database is a mechanism to ensure data consistency when the database data is high concurrency. For example: There are two tickets for ticket sales at the same time, while reading a certain discovery Shanghai to the background ticket balance 5 . At this point two ticket sales at the same time to sell a ticket, while revising the balance to 5-1 4 write back to the database, which resulted in the actual sale of two train tickets and the database records but only a few 1 Zhang. To avoid this, there is a lock mechanism, which is used to forcibly restrict resource access when executing multiple threads.

Third, starting from a simple and practical example to learn INDEXEDDB

To learn INDEXEDDB related knowledge, you can go to MDN document chewing API, in time can become the front-end INDEXEDDB experts. But this kind of learning method is long, too painful, can not be immediate, because the API is too much, every day spent a few hours, it is estimated that it will take weeks to fully transparent.

The thought of input-output ratio so low, so I decided to start from the example of learning, to achieve the basic database additions and deletions to check the function is good, basically 80%+ related needs can be calmly done, and then have the opportunity to go further.

Spent a few nights tossing, a have to delete and change without checking the instance page finally out, you can ruthlessly click here: HTML5 indexeddb storage Edit and delete data demo

The first time we went in there was no data, as shown below:

1. At this point, we fill out the form and create a piece of data, as follows:

When you click the "OK Create" button, you get the result as shown:

At this point we refresh the page, which is still the result shown.

Open the console, in Application→indexeddb, we can see information such as data fields and values that are currently stored:

2. We can modify the created data directly, for example, to modify the note information:

After the loss of Coke directly to modify the local database information, we refresh, you can see the note copy has become "a handsome man ~"

3. We can also delete the database data, such as click the Delete button:

As a result, the database data is deleted and the interface is re-displayed as "No data".

The above is the INDEXEDDB of the demo page to add data, edit data and delete data function.

If your current needs are urgent, you can copy the JS source code directly from the demo page and change it, if you want to know more about the INDEXEDDB APIs and their use, keep looking down.

1. First open the INDEXEDDB database

INDEXEDDB database Open is very simple, the syntax is literal meaning:

Window.indexedDB.open (DbName, version);

dbNameis the database name, for example, used in the demo, the ‘project‘ version version of the database, according to my understanding, when we add or modify the database fields, we need to add a version.

In general, opening the INDEXEDDB database is with some callback methods, the code routines are fixed, basically if you use the actual project, you can use similar code:

Database data result var db;//open database var dbopenrequest = window.indexedDB.open (' project ', 1);//Database open after successful dbopenrequest.onsuccess = function (event) {            //Store data result    db = Dbopenrequest.result;    Do other things ...};//the following things are done: The database is first created, or the new version passed by Window.indexedDB.open (the version value is higher than the current) dbopenrequest.onupgradeneeded = function (event) {    //is usually redefined for primary key, field, etc., see demo};

Among them, the most important is the red highlight of the db variable, we all behind the database operations are inseparable from it.

2. Create a primary key and field for the INDEXEDDB database

Before we start the addition of the database, we first have to build the primary key of our database and some fields first. is onupgradeneeded set in this callback method, which executes on the first created version of the database or the indexedDB.open() version number passed in the database method is higher than the current version number.

We do not need to modify the version number of the database to increase the deletion of a row of data in a database. But for field modifications, 5 such as column data, we now change to 6 columns, because the relevant settings are in the onupgradeneeded callback, so we need to increase the version number to trigger the field modification. Demo page This part of the code is as follows:

dbopenrequest.onupgradeneeded = function (event) {    var db = Event.target.result;    Create a database storage object    var objectstore = Db.createobjectstore (DbName, {         keypath: ' id ',        autoincrement:true    }) ;    Defines the data item    objectstore.createindex (' id ', ' id ', {        unique:true        })    of the stored object; Objectstore.createindex (' name ', ' name ');    Objectstore.createindex (' Begin ', ' begin ');    Objectstore.createindex (' End ', ' end ');    Objectstore.createindex (' person ', ' person ');    Objectstore.createindex (' remark ', ' remark ');

Here is a more important concept, called objectStore , this is the INDEXEDDB can replace the Web SQL database is an important advantage, I call "storage object."

objectStore.add()You can add data to a database, objectStore.delete() you can delete data, objectStore.clear() you can empty a database, objectStore.put() you can replace data, and many more operations APIs.

Here, we use objectStore to create the primary key and normal fields of the database.

db.createObjectStoreWhen you create a primary key and return a storage object, the auto-incrementing field is used as the critical path in this demonstration id . createIndex()method can be used to create an index, which can be understood as creating a field with the following syntax:

Objectstore.createindex (IndexName, KeyPath, Objectparameters)

which

IndexName
The name of the index created, which can be indexed with a null name.
KeyPath
The key path used by the index can be empty keyPath , or it keyPath can be passed to an array keyPath .
Objectparameters

Optional parameters. One of the common parameters is unique to indicate whether the field value is unique and cannot be duplicated. For example, this demo id is not repeatable, so there are settings:

Objectstore.createindex (' id ', ' id ', {  unique:true    });
3. INDEXEDDB Database Add data

Once the fields have been built, we can add data to the INDEXEDDB database.

Since the operations of the database are based on transactions (transaction), we have to establish a transaction (transaction) before we can proceed with the following operations, whether it be adding edits or deleting the database. The syntax is the name:

var transaction = db.transaction (DbName, "ReadWrite");

dbNameis the name of the database, and our database add data operations are simple:

Create a new transaction var transaction = db.transaction (' project ', ' ReadWrite ');//Open Storage object var objectstore = Transaction.objectstore (' Project ');//Added to the data Object Objectstore.add (NewItem);

Using a single line of statements means:

Db.transaction (' project ', ' ReadWrite '). ObjectStore (' project '). Add (NewItem);

This newItem is directly a native pure JavaScript object, in this demo, the newItem data resembles the following:

{  "name": "First item",  "Begin": "2017-07-16", "  End": "2057-07-16",  "person": "Zhang Xin Asahi",  "remark": "Test test "}

It can be found that when we use the INDEXEDDB database to add data, there is no need to learn extra SQL statements, the original JavaScript objects directly seamlessly docking,

4. Editing of the INDEXEDDB database

The principle is, based on the id acquisition of the corresponding row of the storage object, the method is objectStore.get(id) , and then replace the original storage object, and then use objectStore.put(record) to replace the database data.

CODE schematic:

function edit (ID, data) {    //new transaction    var transaction = db.transaction (' project ', "ReadWrite");    Open an already stored data object    var objectstore = Transaction.objectstore (project);    Gets the stored object that stores the corresponding key    var objectstorerequest = objectstore.get (ID);    Get successful replace current data    objectstorerequest.onsuccess = function (event) {        //Current data        var Myrecord = Objectstorerequest.result;        Traverse Replace for        (var key in data) {            if (typeof Myrecord[key]! = ' undefined ') {                Myrecord[key] = Data[key];            }        }        //Update database storage data                     objectstore.put (Myrecord);}    ;}

Where is the id field value of the database row to be replaced id , because the unique primary key guarantees accuracy and performance, and data is the data object that needs to be replaced, such as from test test to be handsome ~, then call:

Edit (1, {  remark: ' is a handsome ~ '});

You can, and we usually write JS code there is no difference.

5. Deletion of the INDEXEDDB database

As opposed to adding, but the code structure is similar, one line notation:

Db.transaction (' project ', ' ReadWrite '). ObjectStore (' project '). Delete (ID);

idIndicates that id the value of the row field needs to be deleted.

5. Access to the INDEXEDDB database

The INDEXEDDB database is obtained using cursor APIs and key Range APIs.

That is, using the cursor API and the scope API. In the demo page of this article, only the cursor API is used to display all the data directly, but it is not used for the scope API, but it is also described briefly here.

The cursor API allows us to read the database data in one row, with the code indicating:

var objectstore = db.transaction (dbName). ObjectStore (DbName); Objectstore.opencursor (). onsuccess = function (event) {    var cursor = Event.target.result;    if (cursor) {        ///Cursor.value is the data object        //cursor is not traversed, continue to        cursor.continue ();    } else {        //If all traversal is complete ...    }}

As you can see, we use the open cursor of the storage object to openCursor() onsuccess traverse our Cursor object in the callback. cursor.valueThis is the complete data object, the pure JS object, just like this:

{  "id": 1,  "name": "First item",  "Begin": "2017-07-16",  "End": "2057-07-16",  "person": "Zhang Xin Xu",  "Remark": "Test Test"}

We can display our data as needed.

"Scope API" is used with the "cursor API", see the following example, only open id data from the 4~10, then there are:

Determine the primary key range of the open cursor var keyrangevalue = Idbkeyrange.bound (4, 10);//Open the corresponding range of the cursor var objectstore = db.transaction (dbName). ObjectStore (DbName); Objectstore.opencursor (keyrangevalue). onsuccess = function (event) {    var cursor = Event.target.result;    // ...}

Among them, there, bound() only() , Lowerbound () and upperBound() These methods, means the method name literal meaning, "within", "just", "less than a certain value" and "greater than a certain value".

The two Boolean parameters are also supported at the end of the method, for example:

Idbkeyrange.bound (4, ten, True, true)

The range 3~9 , that is, true cannot be equal to the range boundary.

Iv. indexeddb storage vs. Localstorage storage
    • INDEXEDDB storage ie10+ Support, Localstorage storage ie8+ support, the latter compatibility is better;
    • INDEXEDDB storage is more suitable for key value pairs of data, I have a lot of items need to store more than one field, using Localstorage storage, the results of each write and write are both string and object, very cumbersome, if the use of INDEXEDDB will be much easier, because there is no need for data conversion.
    • INDEXEDDB storage can be used in workers, Localstorage seems to be unavailable. This makes it possible for the data storage technology selection to fall on the INDEXEDDB storage at the time of PWA development.

In summary, if it is the browser main form thread development, while the storage data structure is simple, for example, to save a true/false , obviously on the election localStorage ; If the data structure is more complex and there is no requirement for browser compatibility, consider using INDEXEDDB; if the service Workers, you can only use INDEXEDDB data storage in the development of applications.

V. Concluding remarks

The use of the INDEXEDDB database can now be used directly under the HTTP protocol, which must be different from the cacheStorage HTTPS protocol used by the cache store. So in terms of application scenarios, INDEXEDDB database is quite broad, considering the IE10 also support, so the basic can be determined in the actual project application is absolutely no problem.

For example, some of the unstructured structured data on the page can be stored locally using the INDEXEDDB database, helping to enhance the interactive performance of the page. cacheStoragecache page, INDEXEDDB database cache data, the combination of the two can achieve hundred off-line development, sounds still very powerful.

The content is more, time is more hurried, the expression has the mistake inevitably, welcome the big correction.

Thanks for reading, Welcome to Exchange!

Reference article:

    • Migrating your websql DB to IndexedDB
    • Database transactions
    • relational database and non-relational database
    • Database-Cursors

HTML5 INDEXEDDB front-end local storage DB Instance tutorial (reprint)

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.