In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
Preface
In the local storage of HTML5, there is a database called indexedDB, which is a NoSQL database stored locally on the client side, 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, but for a large number of structured storage, the advantage of indexedDB is more obvious. Next let's take a look at how indexedDB stores data.
Original author: Lin Xin, author blog: https://github.com/lin-xin/blog
Connect to the 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 through the database name.
Var request = indexedDB.open ('dbName', 1); / / Open dbName database request.onerror = function (e) {/ / execute console.log when listening to the database failed (' failed to connect to the database');} request.onsuccess = function (e) {/ / execute console.log when the connection to the database is successful ('connect to the database');}
We use the indexedDB.open method to connect to the database, which takes two parameters, the first is the database name, and the second is the database version number. This method returns an IDBOpenDBRequest object that represents a request object that requests to connect to the database. We can define the method to be executed for a successful or failed connection by listening for the onsuccess and onerror events of the request object.
Because the data warehouse in the database is not allowed to change in the same version in indexedDB API, you need to pass a new version number in the indexedDB.open method to update the version to avoid repeatedly modifying the database in the same version. The version number must be an integer!
Var request = indexedDB.open ('dbName', 2); / / newer version, open the database with version 2 / /... request.onupgradeneeded = function (e) {console.log (' new database version number ='+ e.newVersion);}
We define the method to be executed when the database version is updated by listening for the onupgradeneeded event of the request object.
Shut down the database
An IDBOpenDBRequest object is returned after a successful connection to the database using indexedDB.open, and we can call the close method of that object to close the database.
Var request = indexedDB.open ('dbName', 2); / /... request.onsuccess = function (e) {console.log (' database connected successfully'); var db = e.target.result; db.close (); console.log ('database closed');} delete database indexedDB.deleteDatabase ('dbName'); console.log (' database deleted'); create object repository
Object store (object Warehouse) is the foundation of indexedDB database, there is no database table in indexedDB, and object warehouse is equivalent to 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 (' object repository created successfully');}
The db.createObjectStore method takes two parameters, the first is the object repository name, the second 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 as the primary key in the database table. If the autoIncrement property is false, it means that the primary key value is not self-increasing, and the primary key value needs to be specified when adding data.
Note: in the database, the object repository name can not be repeated, otherwise the browser will report an error.
Create an index
An index is created by an attribute of a data object in the indexedDB database, and when retrieved in the database, it can only be retrieved through the attribute set as the index.
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 ('index created successfully');}
The store.createIndex method takes three parameters, the first is the index name, the second is the property of the data object, in the above example, the userName property is used to create the index, and the third parameter is optional, 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 two pieces of data cannot be the same, or false can be the same.
Transaction based
In indexedDB, all data operations can only be performed within a transaction. After a successful connection to the database, you can start a read-only transaction or a read-write transaction using the transaction method of the IDBOpenDBRequest object.
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 ('transaction ended');} tx.onabort = function (e) {console.log ('transaction aborted');}}
The db.transaction method takes 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 of object repository names. Transaction can operate on any one of the parameters. The second parameter is transaction mode. When readonly is passed, only the object repository can be read, not written. You can input readwrite for read and write operations.
Operation data
Add (): add data. Receives a parameter for the object that needs to be saved to the object repository.
Put (): add or modify data. Receives a parameter for the object that needs to be saved to the object repository.
Get (): get the data. Receives a parameter for the primary key value of the data to be obtained.
Delete (): delete the data. Receives a parameter for the primary key value of the data to be obtained.
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) / / Save data var req2 = store.get (1); / / get data with index userId 1 req2.onsuccess = function () {console.log (this.result.userName); / / linxin} var req3 = store.delete (1) / / Delete data with index 1 req3.onsuccess = function () {console.log ('data deleted successfully'); / / deleted data successfully}}
The function of add and put is similar, except that when put saves the data, if the primary key of the data already has the same primary key in the database, it will modify the object of the corresponding primary key in the database, while using add to save the data, if the primary key already exists, the save will fail.
Retrieve data
We know above that you can get the data using the get () method, but you need to set the 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 repository.
The openCursor method takes two parameters, the first of which is an IDBKeyRange object, which can be created in the following ways:
/ / boundRange represents a collection of primary key values from 1 to 10 (inclusive). / / if the third parameter is true, it does not contain the minimum key value of 1; if the fourth parameter is true, it does not contain the maximum key value of 10. The default is falsevar boundRange = IDBKeyRange.bound (1, 10, false, false); / / onlyRange represents a collection of primary key values. The only () parameter is the primary key, 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 means that the minimum primary key is not included. The default is falsevar lowerRange = IDBKeyRange.lowerBound. / / upperRange represents a collection of primary key values less than or equal to 10. / / the second parameter is optional. True means that the largest primary key is not included. The default is falsevar upperRange = IDBKeyRange.upperBound.
The second parameter of the openCursor method indicates the reading direction of the cursor, which is mainly in the following ways:
Next: the data in the cursor is sorted in ascending order according to the primary key value, and all the data with equal primary key value are read.
Nextunique: the data in the cursor is arranged in ascending order according to the primary key value, and only the first data is read when the primary key value is equal.
Prev: the data in the cursor is sorted in descending order according to the primary key value, and all data with equal primary key value are read.
Prevunique: the data in the cursor is arranged in descending order according to the primary key value, and only the first data is read when the primary key value is equal.
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 (1d10); 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 ('search ended');}
When there is data that meets the retrieval criteria, you can update it through the update method:
Cursor.updata ({userId: cursor.key, userName: 'Hello', age: 18})
You can delete this data through the delete method:
Cursor.delete ()
You can continue to read the next piece of data through the continue method, otherwise you will not continue reading after reading the first piece of data:
Cursor.continue ()
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.