Use instance of the indexedDB database in HTML5, html5indexeddb

Source: Internet
Author: User
Tags createindex

Use instance of the indexedDB database in HTML5, html5indexeddb

Preface

In the local storage of HTML5, there is a database named indexedDB, which is a NoSQL database stored locally on the client, which can store a large amount of data. From the previous article: HTML5 advanced series: web Storage, we know that web Storage can easily and flexibly access simple data locally. However, for a large amount of structured Storage, the advantages of indexedDB are even more obvious. Next, let's take a look at how indexedDB stores data.

Connect to database

A website can have multiple indexedDB databases, but each database name is unique. We need to connect to a specific database through the database name.

Var request = indexedDB. open ('dbname', 1); // open the dbName database request. onerror = function (e) {// when listening for database connection failure, execute console. log ('database connection failed');} request. onsuccess = function (e) {// execute the console when listening for a successful connection to the database. log ('database connected successfully ');}

We use the indexedDB. open Method to connect to the database. This method receives two parameters, the first is the database name, and the second is the database version number. This method returns an IDBOpenDBRequest object, representing a request object requesting database connection. We can use the onsuccess and onerror events of the listening request object to define the methods to be executed for connection success or failure.

Because the indexedDB API does not allow the data warehouse in the database to change in the same version, you need. use the open Method to input a new version number to update the version, so that you do not need to modify the database repeatedly in the same version. The version number must be an integer!

Var request = indexedDB. open ('dbname', 2); // update the version. open the database whose version is 2 //... request. onupgradeneeded = function (e) {console. log ('new database version = '+ e. newVersion );}

We use the onupgradeneeded event of the request object to define the method to be executed when the database version is updated.

Close Database

After you successfully connect to the database using indexedDB. open, an IDBOpenDBRequest object is returned. We can call the close method of this object to close the database.

Var request = indexedDB. open ('dbname', 2 );//... request. onsuccess = function (e) {console. log ('database connected successfully'); var db = e.tar get. result; db. close (); console. log ('database closed ');}

Delete Database

IndexedDB. deleteDatabase ('dbname'); console. log ('database deleted ');

Create an object repository

Object store is the basis of the indexedDB database. There is no database table in indexedDB, and object store is equivalent to a database table.

Var request = indexedDB. open ('dbname', 3 );//... request. onupgradeneeded = function (e) {var db = e.tar get. result; var store = db. createObjectStore ('users', {keyPath: 'userid', autoIncrement: false}); console. log ('object repository created successfully ');}

The db. createObjectStore method receives two parameters. The first parameter is the object repository name, and the second parameter is an optional parameter. The value is a js object. The keyPath attribute in this object is the primary key, which is equivalent to the id of the database table as the primary key. If the autoIncrement attribute is false, the primary key value is not auto-incrementing. When adding data, you must specify the primary key value.

Note: In the database, the object repository name must be unique. Otherwise, the browser reports an error.

Create an index

In the indexedDB database, an index is created based on a certain attribute of the Data Object. During retrieval in the database, the index can only be retrieved Based on the attribute set as the index.

Var request = indexedDB. open ('dbname', 4 );//... request. onupgradeneeded = function (e) {var db = e.tar get. result; var store = db. createObjectStore ('newusers', {keyPath: 'userid', autoIncrement: false}); var idx = store. createIndex ('usernameindex', 'username', {unique: false}) console. log ('index created successfully ');}

Store. the createIndex method receives three parameters. The first parameter is the index name and the second parameter is the attribute of the data object. In the preceding example, the userName attribute is used to create an index. The third parameter is an optional parameter, is a js object. The unique attribute in this object is true, which indicates that the index value cannot be the same, that is, the usernames of the two data cannot be the same, and the values of false can be the same.

Transaction-based

In indexedDB, all data operations can only be performed in transactions. After successfully connecting to the database, you can use the transaction method of the IDBOpenDBRequest object to enable read-only transactions or read/write transactions.

Var request = indexedDB. open ('dbname', 5 );//... request. onupgradeneeded = function (e) {var db = e.tar get. result; var tx = db. transaction ('users', 'readonly'); tx. oncomplete = function (e) {console. log ('transaction ended ');} tx. onabort = function (e) {console. log ('transaction aborted ');}}

Db. the transaction method receives two parameters. The first parameter can be a string or an array. the string is an object repository name, And the array is an array consisting of the Object repository name, transaction can be used to operate any object warehouse in the parameter. The second parameter is the transaction mode. When you pass in readonly, you can only perform read operations on the object warehouse and cannot perform write operations. You can input readwrite to perform read and write operations.

Operation data

  1. Add (): add data. Receives a parameter, which is an object that needs to be saved to the object repository.
  2. Put (): Add or modify data. Receives a parameter, which is an object that needs to be saved to the object repository.
  3. Get (): get data. Receives a parameter, which is the primary key value of the data to be obtained.
  4. Delete (): delete data. Receives a parameter, which is the primary key value of the data to be obtained.
Var request = indexedDB. open ('dbname', 5 );//... request. onsuccess = function (e) {var db = e.tar get. result; var tx = db. transaction ('users', 'readwrite'); var store = tx. objectStore ('users'); var value = {'userid': 1, 'username': 'linxin ', 'age': 24} var req1 = store. put (value); // Save the data var req2 = store. get (1); // obtain the req2.onsuccess = function () {console. log (this. result. userName); // linxin} var req3 = store. delete (1); // delete req3.onsuccess = function () {console. log ('data deleted successfully'); // data deleted successfully }}

The function of add and put is similar. The difference is that when put saves data, if the primary key of the data already has the same primary key in the database, the corresponding primary key object in the database will be modified, use add to save the data. If the primary key already exists, the data cannot be saved.

Retrieve Data

We know that the get () method can be used to obtain data, but the primary key value needs to be specified. If you want to obtain data in a range, you can use a cursor. The cursor is created and opened through the openCursor method of the Object repository.

The openCursor method receives two parameters. The first parameter is the IDBKeyRange object. The object creation method mainly includes the following:

// BoundRange indicates the set of primary key values from 1 to 10 (including 1 and 10. // If the third parameter is true, the minimum key value 1 is not included. If the fourth parameter is true, the maximum key value 10 is not included. The default value is falsevar boundRange = IDBKeyRange. bound (1, 10, false, false); // onlyRange indicates a set of primary key values. The only () parameter is the primary key value, an integer type. Var onlyRange = IDBKeyRange. only (1); // lowerRaneg indicates a set of primary key values greater than or equal to 1. // The second parameter is optional. If it is true, the minimum primary key 1 is not included. If it is false, the minimum primary key 1 is included. The default value is falsevar lowerRange = IDBKeyRange. lowerBound (1, false); // upperRange indicates a set of primary key values smaller than or equal to 10. // The second parameter is optional. true indicates that the maximum primary key 10 is not included, and false indicates that the maximum primary key 10 is included. The default value is falsevar upperRange = IDBKeyRange. upperBound (10, false );

The second parameter of the openCursor method indicates the cursor's read direction, mainly including the following:

  1. Next: Data in the cursor is sorted in ascending order of primary key values. data with the same primary key value is read.
  2. Nextunique: the data in the cursor is sorted in ascending order by the primary key values. If the primary key values are equal, only the first data is read.
  3. Prev: the data in the cursor is sorted in descending order by the primary key value. data with the same primary key value is read.
  4. Prevunique: the data in the cursor is sorted in descending order by the primary key values. If the primary key values are equal, only the first data is read.
Var request = indexedDB. open ('dbname', 6 );//... request. onsuccess = function (e) {var db = e.tar get. result; var tx = db. transaction ('users', 'readwrite'); var store = tx. objectStore ('users'); var range = IDBKeyRange. bound (1, 10); var req = store. openCursor (range, 'Next'); req. onsuccess = function () {var cursor = this. result; if (cursor) {console. log (cursor. value. userName); cursor. continue ();} else {console. log ('retrieval terminate ');}}}

When there is data that meets the search criteria, you can update the data using the update method:

cursor.updata({    userId : cursor.key,    userName : 'Hello',    age : 18});

You can delete the data by using the delete method:

cursor.delete();

You can continue reading the next data by using the continue method. Otherwise, you will not continue reading the first data after reading it:

cursor.continue();

Summary

The complete data access process of indexedDB is completed from connecting to the database, creating an object warehouse and index, to operations and data retrieval. The following is a complete example to better master the indexedDB database. Code address: indexedDB-demo

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.