In the local storage of HTML5, there is a database called IndexedDB. The database is a NOSQL database stored on the client that can store a large amount of data. From the previous part: HTML5 advanced series: Web Storage, we know that web storage can easily access simple data in local access, but for a large number of structured storage, the advantages of INDEXEDB are even more obvious. Next, let's take a look at how IndexedDB stores data.
Connect databaseOne website can have multiple IndexedDB databases, but the name of each database is unique. We need to connect a specific database through the database name.
var research = indexeddb.open ('dbname', 1); // Open the dbname database request.onerror = function (e) {// When listening to the database failure, execute console.log ('Connection database failure');} Request. onSuccess = Function (E) {// When the database is successful, execute Console.log ('Connection database success');}
We use the indexeddb.open method to connect the database. This method receives two parameters. The first is the database name and the second is the database version number. This method will return an IDBOPENDBREQUEST object to represent a request object that requests a database. We can define the method where the connection is successful or fails to execute by monitoring the ONSUCCCcess and OneRROR events of the request object.
Because the data warehouse in the database does not allow the database warehouse to change in the same version, the new version number is required to update the version in the indexeddb.open method to avoid repeatedly modified the database in the same version. The version number must be an integer!
var research = indexeddb.open ('dbname', 2); // Update the version, open the database with 2 2 database // ... Request.onupGradeneeded = Function (E) {console.log ('New database version number is = is = is = = ' + e.newversion);}
We define the method executed when the database version is updated by monitoring the onupgradeneeded event of the request object.
Turn off the databaseAfter using indexedb.open to connect to the database success, a Idbopendbrequest object will be returned. We can call the close method of the object to turn off the database.
var research = indexeddb.open ('dbname', 2); // ... request.onsuccess = function (e) {console.log ('Connection database success'); var db = e.target.Result; db. close (); console.log ('The database has been closed');}Delete the database
indexeddb.deletedatabase ('dbname'); console.log ('The database has been deleted');Create object warehouse
Object Store is the basis of the INDEXEDDB database. There is no database table in IndexedDB, and the object warehouse is equivalent to a database table.
var research = indexeddb.open ('dbname', 3); // ... Request.onupGradeneeded = Function (e) {var db = e.target.Result; vartore = db.createObjectStore (' Users', {keypath : 'userid', autoincrement: false}); console.log ('Create object warehouse success');}
DB.CreateObjectStore method receives two parameters. The first is the object warehouse name, the second parameter is optional parameter, and the value is a JS object. The keypath property in this object is the main key, which is equivalent to the ID in the database table as the main key. The AutoIincRement attribute is FALSE, which means that the main key value does not increase by itself. When adding data, you need to specify the main key value.
Note: In the database, the object warehouse name cannot be repeated, otherwise the browser will report an error.
Create an indexIn the IndexedDB database, an index is created through a certain attribute of the data object. When searching in the database, it can only be retrieved by the attribute setting as an index.
var research = indexeddb.open ('dbname', 4); // ... Request.onupGradeneeded = Function (e) {var db = e.target.Result; vartore = db.createObjectStore (' newusers', {keypath : 'userid', autoincrement: false}); var IDX = Store.createINDEX ('usernameindex', 'username', {unique: false}) console.log ('Create index success') ;}
The Store.CreateIndex method receives three parameters. The first is the index name, and the second is the attribute of the data object. In the previous example, the username attribute is used to create the index. The third parameter is optional parameter and the value is a JS object. The Unique property in this object is True, which means that the index value cannot be the same, that is, the username of the two data cannot be the same, and FALSE can be the same.
AffairsIn IndexedDB, all data operations can only be performed in affairs. After the database is successful, you can use the Transaction method of the IDBOPENDBREQUEST object to open only reading or reading and writing transactions.
var research = indexeddb.open ('dbname', 5); // ... Request.onupGradeneeded = Function (e) {var db = e.target.Result; var tx = db.transactions ',' Readonly '); tx.OnComplete = Function (E) {console.log (' The transaction is over ');} tx.onabort = function (e) {console.log (' transaction has been suspended ');}}
The DB.TRANSACTION method receives two parameters. The first parameter can be a string or array, the string is an object warehouse name, and the array of the object warehouse in the array is The warehouse is operated. The second parameter is the transaction mode. When it is transmitted into the Readonly, it can only read the operation of the object warehouse and cannot write the operation. Can be transmitted into the ReadWrite for reading and writing operations.
Operating datavar research = indexeddb.open ('dbname', 5); // ... Request.onsuccess = Function (e) {var db = e.target.Result; var tx = db.transactions ('users',', ',', ',' Readwrite '); VAR Store = TX.ObjectStore (' users'); var value = {'userid': 1, 'username': 'linxin', 'Age': 24} var reput (value); / / Save data var repk2 = store.get (1); // Get the data reQ2.onsuccess = Function () {console.log (this.Result.username); // linxin} Var Req3 = Store. delete (1); // Delete the data of the index 1 data reQ3.onsuccess = function () {console.log ('Delete data success'); // Delete data success}}}}}}}}}}}}}}}}}
The role of ADD and PUT is similar. The difference is that when PUT saves the data, if the main key of the data already has the same primary key in the database, it will modify the corresponding object of the main key in the database, and use ADD to save the data. If the primary key already exists existing The preservation failed.
Retrieval dataWe know above can obtain data using the GET () method, but the main key value is needed. If we want to obtain a range of data, we can use a cursor. The cursor was created and opened by the OPENCURSOR method of the object warehouse.
The OpenCursor method receives two parameters. The first is the IDBKEYRANGE object. The method of creating the object is mainly the following:
// BoundRange represents a collection of primary key values from 1 to 10 (including 1 and 10). // If the third parameter is True, it means that the minimum key value is not 1. If the fourth parameter is TRUE, it means that it does not contain the maximum key value 10, and the default is falsevar boundrange = IDBKEYRANDE.BOUND (1, 10, false false , false); // onlyRange indicates a collection of a main key value. The only () parameter is the main key value, an integer type. varmingRange = IDBKEYRANGE.ONLY (1); // LOWERRANEG represents a collection of primary key values greater than or equal to 1. // The second parameter is optional, which means that True does not include minimum primary key 1, FALSE is included, and defaults to falsevar logerrange = IDBKEYRANGE. LOWERBOUND (1, FALSE); // UPPERRANGE indicates a set of the main key value of the primary key value less than 10 Essence // The second parameter is optional, which means that True does not include the largest primary key 10, and false includes, and the default is falsevar upperRange = idbKeyrange.UPEPERBOUND (10, False);
The second parameter of the OpenCursor method represents the reading direction of the cursor. There are mainly the following:
var research = indexeddb.open ('dbname', 6); // ... Request.onsuccess = Function (e) {var db = e.target.Result; var tx = db.transactions ('users', ',', ',', ',' Readwrite '); Var Store = TX.ObjectStore (' Users'); Var Range = IDBKEYRANGE.BOUND (1,10); VAR REQ = Store.opencursor (Range, 'Next'); ction () {var cursor = this.Result; if (cursor) {console.log (cursor.value.username); cursor.Continue ();} else {console.log ('retrieval end');}}}}
When there is a data that meets the search conditions, you can update the data through the update method:
Cursor.updata ({userid: cursor.Key, username: 'hello', age: 18});
This data can be deleted through the delete method:
cursor.delete ();
You can continue to read the next data through the constinue method, otherwise you will not continue to read after reading the first piece of data:
cursor.continue ();Summarize
From connecting databases, creating object warehouses, indexes, to operation and retrieval data, complete the complete process of IndexedDB access data. Below through a complete example to better grasp the INDEXEDDB database. Code address: IndexedDB-Demo
The above is all the contents of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support VEVB Wulin.com.