HTML5 Local Database (i)

Source: Internet
Author: User

Local Database

Local Database Local Database concepts

An important feature of HTML5 is the persistence of local data, which, in combination with the application cache, can work properly offline. In addition, local data persistence makes mobile applications more responsive, uses less bandwidth, and works more efficiently in low-bandwidth scenarios. HTML5 provides some local data persistence options. The first option is Localstorage, which allows you to store data using a simple key-value pair. INDEXEDDB enables you to store a large number of objects locally and retrieve data using robust data access mechanisms. We'll explain indexeddb in this section.

Determine if the browser supports

INDEXEDDB is the object in window, so use the following code to determine

 //判断浏览器是否支持本地存储    if (window.indexedDB) {        alert("支持");    } else {        alert("不支持");    }
New Database

Use the Open method to create a new database with the following code

var request = window.indexedDB.open("数据库名称", 版本号);
The role of the Open method

The role of the open method is to create a new or open database, and if the specified database does not exist, the database is created, and if it already exists, open the database

Open method Parameters

Open method accepts two parameters

    • The first parameter is the name of the database. Because a Web site can have multiple local databases, make sure that the database name is unique
    • The second parameter is the database version number. Every time you change the structure of a database, such as adding, modifying, and deleting storage objects (tables), change the version number

Here we focus on the version number of the attention point.

    • The version number can only be increased and not reduced. For example, the last call to the Open method, the incoming version number is 2, call again when modified to 1, will be an error
    • The version number can be empty. When the version number is empty, the database is created with a version number of 1
Instance

Run the following code

if (window.indexedDB) {        //注意我们没有写版本号,则默认为1        var request= window.indexedDB.open("db1");    } else {        alert("不支持");    }

Let's take a look at whether the database was created successfully, take chrome as an example, press F12 or FN+F12, open the Developer tool, select the "Resources" tab

We see the indexeddb on the left, unfold to see

This db1 is the database we just created, the right side is the database information, respectively, the domain that the database belongs to, the name and version number

This is if we execute the above code again, we will not create the DB1 database again, but open it, because this database already exists

Modify the code above to change the version number to 2

 if (window.indexedDB) {        //注意我们没有写版本号,则默认为1        var request= window.indexedDB.open("db1",2);    } else {        alert("不支持");    }

Execute this code again and see the INDEXEDDB change in the developer tool (note that you will not see the change until you refresh it.) Refresh method: Right button on IndexedDB-"Refresh IndexedDB")

However, if you now want to upgrade the database version again, you should change the database version number to >2 number, if you change to <2 number, such as 1, it will not have any effect

Get the database created

Once the database is created, we need to get a reference to the database that was created to manipulate the database, such as creating objectstore (table), manipulating data, and so on.

Did we notice the return value of the Open method request? However, it is a reference to the database, the open method just sends a request to the browser, request new or open a database, object request has three important events, we can write different code in these events according to different circumstances, first of all, we are familiar with these events

    • OnError: This event is called when an error occurs when calling the open method, such as the version number in the Open method is lower than the version number of the database
    • Called when the Onsuccess:open method executes successfully, such as successfully creating a new database or successfully opening an existing database
    • Onupgradeneeded: This event is called only if a new database and database version number has changed. Note: This event occurs before the Onsuccess event

Summary: The operation of Objectstroe, such as Create, modify, delete operations should be placed in the Onupgradeneeded event, but not in the Onsuccess event, these operational data database structure changes, belong to the upgrade operation, The Onsuccess event executes every time the open method is executed, and the Open method is called only to add a single piece of data.

Let's write the complete code.

window.onload = function() {        //声明变量用来存储数据库的引用        var mydb;    //判断浏览器是否支持本地存储    if (window.indexedDB) {                   //注意我们没有写版本号,则默认为1        var request = window.indexedDB.open("db1", 2);        request.onerror = function(e) {            console.log("打开数据库时发生错误");        };        request.onsuccess = function(e) {            mydb = e.target.result;            console.log("打开数据库成功");        };        request.onupgradeneeded = function(e) {            mydb = e.target.result;            console.log("数据库版本变更成功");        };    } else {        alert("不支持");    }}

The Console.log method is to output content in the console for debugging

E.target.result gets a reference to the database, we declare a global variable MYDB to store the reference.

This is a relatively complete structure using the INDEXEDDB database, and we'll create the ObjectStore

Creating Objectstoreobjectstore Concepts

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 rather objectstore, I myself translated into the object repository, 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.

So what is this key?

What is the key

In ObjectStore, data is stored in a different way from a traditional relational database. For example, to store the following information

A person's name is Zhang San, age is 20, sex is male, birthplace is Baoding

The traditional relational database is stored in this way: first create a field in a table, and then add values below each field (given that each table must have a primary key principle, we must also add a business-independent column, such as an ID), as

Age
ID name Gender Address
1 Tom 20 Man Baoding

OK, this ID column is equivalent to the key in the ObjectStore to uniquely identify each piece of data.

However, in ObjectStore, data is not represented in this way, but data is stored as a key-value pair

{name: "Zhang San", Age:20,gender: "Male", Address: "Baoding"}

We will think, if there is another identical data to do (the same name, want to the same grade, the same sex, the same place of people too many), if one day we want to find Zhang San, in the end to find Which?

So there's a key concept in ObjectStore, so let's take a look at how the key is specified in INDEXEDDB.

In Indexeddb, the key has the following type

Key Type Storing Data
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

We do not faint, today we only introduce a kind of, keypath, the rest of the people themselves can read it. KeyPath means using one of the specified fields in each record as the key value (KeyPath), such as the above data

{name: "Zhang San", Age:20,gender: "Male", Address: "Baoding"}

Let's change it, add an ID

{ID: "1001", Name: "Zhang San", Age:20,gender: "Male", Address: "Baoding"}

We use the value of the ID as a key that uniquely identifies the data, and we can do so using the KeyPath method, which will be described in the use of the Create ObjectStore

Create ObjectStore

Modify the code in the Onupgradeneeded event

 request.onupgradeneeded = function(e) {            mydb = e.target.result;            if (!mydb.objectStoreNames.contains("student")) {                mydb.createObjectStore("student", {                    keyPath: "id"                });            };        };

The Mydb.objectStoreNames.contains method is used to determine if there is a objectstore in the database with the name student, and if none is created

The Createobjectstore method is used to create the ObjectStore, which accepts two parameters, the first parameter is the ObjectStore name, and the second is the value of the key specified for the ObjectStore, {keypath: "id"} The student uses the KeyPath type key, which is the value of the ID field in the database.

Of course, before executing this code, do not forget to modify the version number in the Open method, otherwise this event will not be executed (what, I said)

Look (don't forget to right-click to refresh)

Maybe now you're not very clear about the "key" concept, okay, and below we insert two data, a look at the data you will understand

Inserting data transactions into the ObjectStore

Before you manipulate the data (note that it is not the database), you need to start a transaction. The transaction needs to specify which object store the transaction spans. That is, any manipulation of the data in the ObjectStore is in the transaction

There are three modes of transactions

    • Read only: Read, cannot modify database data, can execute concurrently
    • Read and write: ReadWrite, can read and write operations
    • Version changed: Verionchange

Let's look at how the code is implemented

Add a button to the HTML and click this button to insert the data into the ObjectStore named student

<body><input type="button" name="btnAdd" id="btnAdd" value="插入数据"></body>

To add a Click event for this button, the code is as follows

document.getElementById("btnAdd").onclick = function() {        //创建要添加的数据        var student = {            id:"1001",            name: "张三",            age: 20,            gender: "男",            address: "保定"        };        //创建针对student的事务        var transaction = mydb.transaction(["student"], "readwrite");        //从事务中获取要操作的objectstore        var obj = transaction.objectStore("student");        //添加数据        obj.add(student);        console.log("数据添加成功");    }

We have pieced together a set of key-value pairs as data to be inserted into student, because ObjectStore only accepts data in this format, remember the value of the ID first

The Mydb.transaction method is used to open the transaction, which accepts two parameters, the first is the name of the ObjectStore associated with the transaction, and note that [] is used because a transaction can have more than one objectstore, and the second parameter indicates that the transaction is readable and writable. That is, you can read and write data in this transaction.

The Transaction.objectstore ("student") method gets the ObjectStore to manipulate in the transaction

The Obj.add (student) method is used to insert data into the ObjectStore

After clicking the button, refresh the INDEXEDDB to see the results

We see that the value of key is the value of the ID in the value pair.

Add more than one piece of data

If you want to add more than one piece of data, we need to modify the code

 document.getElementById("btnAdd").onclick = function() {        //创建要添加的数据        var student = [{            id: "1002",            name: "张三",            age: 20,            gender: "男",            address: "保定"        }, {            id: "1003",            name: "李四",            age: 21,            gender: "男",            address: "国际庄"        }, {            id: "1004",            name: "李丹",            age: 22,            gender: "女",            address: "保定"        }];        //创建针对student的事务        var transaction = mydb.transaction(["student"], "readwrite");        //从事务中获取要操作的objectstore        var obj = transaction.objectStore("student");        //添加数据        for (var i = 0; i < student.length; i++) {            obj.add(student[i]);        };        console.log("数据添加成功");    }

Effect

Think: Why is the value of this ID starting at 1002 instead of 1001? Try it yourself.

Querying data

The query here can only be based on the value of the key query, not like the traditional database, can be based on any one key value, such as name, age and other queries, if you want to achieve this effect, you need to cooperate with the index and cursor in INDEXEDDB

We'll start with the key value query.

Add a button to query the data

document.getElementById("btnQuery").onclick = function() {        var transaction = mydb.transaction(["student"], "readwrite");        var obj = transaction.objectStore("student");        var request = obj.get("1002");        request.onsuccess = function() {            console.log("id为1002的人的姓名为" + request.result.name);        }    }

The function of the Obj.get method is to store the value of the ObjectStore request key with the name student in the database as 1002 corresponding to the data, and the result of the request is stored in the Request.result attribute.

We then get the value of name in the Onsuccess event.

We can output the value of Request.result to see

request.onsuccess = function() {            //console.log("id为1002的人的姓名为" + request.result.name);            console.log(request.result);        }

The results are as follows

Update data

Add a button to update the data, the code is very simple, directly on the code

document.getElementById("btnUpdate").onclick = function() {        var transaction = mydb.transaction(["student"], "readwrite");        var obj = transaction.objectStore("student");        var request = obj.get("1002");        request.onsuccess = function() {            request.result.name="哈哈";            obj.put(request.result);                     }    }

As with the query method, you still need to operate in the Onsuccess event, first change the value of Request.result.name to the new value, and then update the database with the put method of the Obj object

View the results and find that the values have changed

Delete data

Deleting data is the simplest

document.getElementById("btndel").onclick = function() {        var transaction = mydb.transaction(["student"], "readwrite");        var obj = transaction.objectStore("student");        obj.delete("1002");               }

Results

Deleting a database

The database can also be deleted

document.getElementById("btndeldb").onclick = function() {        //关闭数据库连接        mydb.close();        indexedDB.deleteDatabase("db1");           }

You should call the Close method to close the current database connection before deleting it, and then call the Indexeddb.deletedatabase method to delete it based on the name of the database.

The Complete case

The following is a complete case, note that the first run should change the version number of the database to 1

<! DOCTYPE html>

Resources

Http://www.cnblogs.com/smileberry/p/3844269.html

Http://www.cnblogs.com/dolphinX/p/3415761.html

http://www.ibm.com/developerworks/cn/web/wa-indexeddb/

http://www.thinksaas.cn/group/topic/349664/

HTML5 Local Database (i)

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.