Objective
In HTML5 's local storage, there is a database called IndexedDB, which is a NoSQL database that is stored locally on the client, and it can store a large amount of data. From previous: HTML5 Advanced Series: Web Storage, we know that Web Storage can easily and flexibly access simple data locally, but for a lot of structured storage, the advantages of IndexedDB are even more obvious. Next, let's look at how IndexedDB stores the data.
Hara Wenlingxin, author blog: Https://github.com/lin-xin/blog
Connecting to a database
A Web site can have multiple IndexedDB databases, but the name of each database is unique. We need to connect to a specific database by the name of the database.
var request = Indexeddb.open (' DbName ', 1); Open DbName Database Request.onerror = function (e) {//Listen to connection database failed when executing console.log (' Connection database failed ');} request.onsuccess = function (e) {//listens to the connection database successfully when executing console.log (' Connect database succeeds ');}
We use the Indexeddb.open method to connect to the database, which receives two parameters, the first is the database name, and the second is the database version number. The method returns a Idbopendbrequest object that represents a request object that requests a connection to the database. We can define how the connection succeeds or fails by listening to the onsuccess and onerror events of the request object.
Because the IndexedDB API does not allow data warehouses in the database to change in the same version, the new version number needs to be passed in the Indexeddb.open method to update the version, avoiding the need to repeatedly modify the database in the same version. The version number must be an integer!
var request = Indexeddb.open (' DbName ', 2); Update version, open a database of version 2//... request.onupgradeneeded = function (e) {console.log (' new database version number = ' + e.newversion);}
We define the method that executes when the database version is updated by listening to the onupgradeneeded event of the request object.
Close the database
Using Indexeddb.open to connect to a database succeeds in returning a Idbopendbrequest object, and we can call the Close method of the object to close the database.
var request = Indexeddb.open (' DbName ', 2);//... request.onsuccess = function (e) {console.log (' connection to database succeeded '); var db = E.target.result; Db.close (); Console.log (' database closed ');}
Deleting a database
Indexeddb.deletedatabase (' DbName '); Console.log (' database deleted ');
Create an Object warehouse
The object store is the base of the IndexedDB database, and in IndexedDB there is no database table, and the object repository is the equivalent of a database table.
var request = Indexeddb.open (' DbName ', 3);//... request.onupgradeneeded = function (e) {var db = E.target.result; var store = Db.createobjectstore (' Users ', {keypath: ' UserId ', autoincrement:false}); Console.log (' Create object repository succeeded ');}
The Db.createobjectstore method receives two parameters, the first is the object warehouse name, the second parameter is an optional parameter, and the value is a JS object. The KeyPath property in this object is the primary key, which is equivalent to the ID in the database table. The AutoIncrement property is false, which means that the primary key value is not self-increasing and the primary key value is specified when the data is added.
Note: In the database, the object warehouse name is not duplicated, otherwise the browser will error.
Create an index
An index is created in the IndexedDB database through a property of a data object that can be retrieved only through the indexed properties when it is retrieved in the database.
var request = Indexeddb.open (' DbName ', 4);//... request.onupgradeneeded = function (e) {var db = E.target.result; var store = Db.createobjectstore (' newusers ', {keypath: ' UserId ', autoincrement:false}); var idx = store.createindex (' Usernameindex ', ' UserName ', {unique:false}) Console.log (' Create index succeeded ');}
The Store.createindex method receives three parameters, the first is the index name, the second is the property of the data object, the previous example uses the UserName property to create the index, the third parameter is an optional parameter, and the value is a JS object. The unique attribute in the object is true, which means that the index value cannot be the same, that is, the userName of two data cannot be the same, or false.
Transaction-based
In IndexedDB, all data operations can only be performed in a transaction. After a successful connection to the database, you can use the transaction method of the Idbopendbrequest object to open a read-only transaction or read-write transaction.
var request = Indexeddb.open (' DbName ', 5);//... request.onupgradeneeded = function (e) {var db = E.target.result; var tx = db.transaction (' Users ', ' ReadOnly '); Tx.oncomplete = function (e) {console.log (' End of transaction '); } Tx.onabort = function (e) {console.log (' transaction aborted '); }}
The Db.transaction method receives two parameters, the first argument can be a string or an array, a string is an object warehouse name, an array is an array of object warehouse names, and transaction can manipulate any of the object warehouses in the parameter. The second parameter is the transaction pattern, which can only be read to the object repository when the ReadOnly is passed in, not write operations. You can pass in ReadWrite for read and write operations.
Manipulating data
Add (): Add data. Receives an argument for an object that needs to be saved to the object repository.
Put (): Adds or modifies data. Receives an argument for an object that needs to be saved to the object repository.
Get (): Gets the data. Receives a parameter, which is the primary key value that needs to get the data.
Delete (): Deletes the data. Receives a parameter, which is the primary key value that needs to get the data.
Var request = indexeddb.open (' DbName ', 5);// ...request.onsuccess = Function (e) { var db = e.target.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); // saving data var req2 = store.get (1); // get the data for index UserID 1 req2.onsuccess = function () { &Nbsp; console.log (This.result.userName); // linxin } var req3 = store.delete (1); // Delete data with index 1 req3.onsuccess = function () { console.log (' Delete data success '); // Delete data successfully }}
Add and put act similarly, the difference is that when the put holds the data, if the primary key of the data already has the same primary key in the database, it modifies the object corresponding to the primary key in the database, and uses the add to save the data, and if the primary key already exists, the save fails.
Retrieving data
Above we know that using the Get () method can fetch data, but you need to make a primary key value. If we want to get a range of data, we can use cursors. Cursors are created and opened through the OpenCursor method of the object warehouse.
The OpenCursor method receives two parameters, the first of which is the Idbkeyrange object, which is mainly created in the following ways:
The Boundrange represents a collection of primary key values from 1 to 10 (containing 1 and 10). If the third argument 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 is Falsevar Boundrange = Idbkeyrange.bound (1, False, False) ;//Onlyrange represents a collection of primary key values. The only () parameter is the primary key value, and the integer type. var onlyrange = idbkeyrange.only (1);//Lowerraneg represents a collection of primary key values greater than or equal to 1. The second parameter is optional, true to indicate that no minimum primary key 1,false is included, the default is Falsevar LowerRange = Idbkeyrange.lowerbound (1, false);//Upperrange Represents a collection of primary key values that are less than or equal to 10. The second parameter is optional, true to indicate that no maximum primary key 10,false is included, the default is Falsevar Upperrange = Idbkeyrange.upperbound (false);
The second parameter of the OpenCursor method represents the reading direction of the cursor, mainly in the following ways:
-
Next: Data in cursors is sorted in ascending order by primary key value, data with primary key value equal is read
-
Nextunique: Data in cursors is sorted in ascending order by primary key value Primary key value equality reads only the first data
-
Prev: Data in cursors is sorted in descending order of primary key values, data with primary key value equal is read
-
Prevunique: Data in cursors is sorted in descending order of primary key values. Primary key value equality reads only the first data
Var request = indexeddb.open (' DbName ', 6);// ...request.onsuccess = Function (e) { var db = e.target.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 (' End of search '); } }}
You can update the data by using the Update method when there is data that matches the search criteria:
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 piece of data through the Continue method, or you will not continue reading after reading the first data:
Cursor.continue ();
HTML5 Advanced Series: IndexedDB database