In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What this article shares to you is the example analysis of HTML5's IndexedDB index database. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
IndexedDB is a HTML5 WEB database that allows HTML5 WEB applications to store data on the user's browser side. IndexedDB is very powerful and useful for applications. It can store a large amount of data in WEB browsers such as chrome,IE,Firefox on the client side.
What is IndexedDB?
IndexedDB,HTML5 's new data storage, which can store and manipulate data on the client, can make applications load faster and respond better. Different from the relational database, it has data tables and records. It affects the way we design and create applications. IndexedDB creates an object with data types and simple JavaScript persistent objects, and each object can have an index, making it efficient to query and traverse the entire collection. This article provides you with a real-world example of how to use IndexedDB in Web applications.
Start
We need to include the following preamble before execution
Var indexedDB = window.indexedDB | | window.mozIndexedDB | | window.webkitIndexedDB | | window.msIndexedDB; / / prefixes of window.IDB objects var IDBTransaction = window.IDBTransaction | | window.webkitIDBTransaction | | window.msIDBTransaction; var IDBKeyRange = window.IDBKeyRange | | window.webkitIDBKeyRange | | window.msIDBKeyRange if (! indexedDB) {alert ("Your browser doesn't support a stable version of IndexedDB.")}
Open IndexedDB
Before creating a database, we first need to create data for the database, assuming that we have the following user information:
Var userData = [{id: "1", name: "Tapas", age: 33, email: "tapas@example.com"}, {id: "2", name: "Bidulata", age: 55, email: "bidu@home.com"}]
Now we need to open our database with the open () method:
Var db; var request = indexedDB.open ("databaseName", 1); request.onerror = function (e) {console.log ("error:", e);}; request.onsuccess = function (e) {db = request.result; console.log ("success:" + db);}; request.onupgradeneeded = function (e) {}
As shown above, we have opened a database named "databaseName" that specifies the version number, and the open () method takes two parameters:
1. The first parameter is the database name, which detects whether a database with the name "databaseName" already exists, opens it if it does, or creates a new database.
two。 The second parameter is the version of the database, which is used by the user to update the database structure.
OnSuccess processing
"onSuccess" is triggered when a successful event occurs, and if all successful requests are processed here, we can save the result of the request for later use by assigning a value to the db variable.
The handler of onerror
"onerror" is triggered when an error event occurs, if the process of opening the database fails.
Onupgradeneeded processor
If you want to update the database (create, delete, or modify the database), then you must implement the onupgradeneeded handler so that you can make any changes in the database. It is the only place in the "onupgradeneeded" processor where the structure of the database can be changed.
Create and add data to the table:
IndexedDB uses object storage to store data, not through tables. Whenever a value is stored in the object store, it is associated with a key. It allows any object we create to store the index. The index allows us to access values stored in the object store. The following code shows how to create an object store and insert preprepared data:
Request.onupgradeneeded = function (event) {var objectStore = event.target.result.createObjectStore ("users", {keyPath: "id"}); for (var i in userData) {objectStore.add (userdata [I]);}}
We use the createObjectStore () method to create an object store. This method accepts two parameters:-the stored name and the parameter object. Here, we have an object store called "users" and define keyPath, which is the uniqueness property of the object. Here, we use "id" as the keyPath, which is unique in the object store, and we must make sure that the property of the "ID" exists in each object in the object store. Once we have created the object store, we can start adding data to it using a for loop.
Manually add data to the table:
We can manually add additional data to the database.
Function Add () {var request = db.transaction (["users"], "readwrite"). ObjectStore ("users") .add ({id: "3", name: "Gautam", age: 30, email: "gautam@store.org"}); request.onsuccess = function (e) {alert ("Gautam has been added to the database."); request.onerror = function (e) {alert ("Unable to add the information.") }}
Before we do any CRUD operation (read, write, modify) in the database, we must use transactions. The transaction () method is used to specify the object store that we want to transact. The transaction () method accepts three parameters (the second and third are optional). The first is the list of object stores we want to deal with, the second specifies whether we want to read / write only, and the third is the version change.
Read data from a table
The get () method is used to retrieve data from the object store. We have previously set the object's id as the keyPath of, so the get () method will look for objects with the same id value. The following code returns the object we named "Bidulata":
Function Read () {var objectStore = db.transaction (["users"]). ObjectStore ("users"); var request = objectStore.get ("2"); request.onerror = function (event) {alert ("Unable to retrieve data from database!");} Request.onsuccess = function (event) {if (request.result) {alert ("Name:" + request.result.name + ", Age:" + request.result.age + ", Email:" + request.result.email);} else {alert ("Bidulata couldn't be found in your database!");}};}
Read all data from the table
The following method retrieves all data in the table. Here we use cursors to retrieve all the data in the object store:
Function ReadAll () {var objectStore = db.transaction ("users"). ObjectStore ("users"); var req = objectStore.openCursor (); req.onsuccess = function (event) {db.close (); var res = event.target.result; if (res) {alert ("Key" + res.key + "is" + res.value.name + ", Age:" + res.value.age + ", Email:" + res.value.email); res.continue () }}; req.onerror = function (e) {console.log ("Error Getting:", e);};}
The openCursor () is used to traverse multiple records in the database. Continue to read the next record in the continue () function.
Delete records from the table
The following method deletes the record from the object.
Function Remove () {var request = db.transaction (["users"], "readwrite"). ObjectStore ("users"). Delete ("1"); request.onsuccess = function (event) {alert ("Tapas's entry has been removed from your database.");};}
We will pass the object's keyPath as an argument to the delete () method.
Final code
The following method deletes a record from the object source:
IndexedDB var indexedDB = window.indexedDB | | window.mozIndexedDB | | window.webkitIndexedDB | | window.msIndexedDB; / / prefixes of window.IDB objects var IDBTransaction = window.IDBTransaction | | window.webkitIDBTransaction | | window.msIDBTransaction Var IDBKeyRange = window.IDBKeyRange | | window.webkitIDBKeyRange | | window.msIDBKeyRange if (! indexedDB) {alert ("Your browser doesn't support a stable version of IndexedDB.")} var customerData = [{id: "1", name: "Tapas", age: 33, email: "tapas@example.com"}, {id: "2", name: "Bidulata", age: 55, email: "bidu@home.com"}]; var db Var request = indexedDB.open ("newDatabase", 1); request.onerror = function (e) {console.log ("error:", e);}; request.onsuccess = function (e) {db = request.result; console.log ("success:" + db);} Request.onupgradeneeded = function (event) {} request.onupgradeneeded = function (event) {var objectStore = event.target.result.createObjectStore ("users", {keyPath: "id"}); for (var i in userData) {objectStore.add (userdata [I]) } function Add () {var request = db.transaction (["users"], "readwrite") .objectStore ("users") .add ({id: "3", name: "Gautam", age: 30, email: "gautam@store.org"}); request.onsuccess = function (e) {alert ("Gautam has been added to the database.");} Request.onerror = function (e) {alert ("Unable to add the information.");}} function Read () {var objectStore = db.transaction ("users"). ObjectStore ("users"); var request = objectStore.get ("2"); request.onerror = function (event) {alert ("Unable to retrieve data from database!");} Request.onsuccess = function (event) {if (request.result) {alert ("Name:" + request.result.name + ", Age:" + request.result.age + ", Email:" + request.result.email);} else {alert ("Bidulata couldn't be found in your database!");}} function ReadAll () {var objectStore = db.transaction ("users"). ObjectStore ("users") Var req = objectStore.openCursor (); req.onsuccess = function (event) {db.close (); var res = event.target.result; if (res) {alert ("Key" + res.key + "is" + res.value.name + ", Age:" + res.value.age + ", Email:" + res.value.email); res.continue ();}} Req.onerror = function (e) {console.log ("Error Getting:", e);} function Remove () {var request = db.transaction (["users"], "readwrite"). ObjectStore ("users"). Delete ("1"); request.onsuccess = function (event) {alert ("Tapas's entry has been removed from your database.");};} Delete record Retrieve all records
Lock
LocalStorage does not have the lock feature. Then in order to achieve the front-end data sharing and need lock function, you need to use other local storage methods, such as indexedDB. IndededDB uses a transaction mechanism, which is actually the lock function.
To do this test, you need to simply encapsulate the operation of indexedDB, because the connection of indexedDB is troublesome, and both test pages need to use
/ / db.js / / encapsulates the transaction operation IDBDatabase.prototype.doTransaction=function (f) {f (this.transaction (["Obj"], "readwrite") .objectStore ("Obj"));}; / / connects to the database, and calls the main function (function () {/ / Open the database var cn=indexedDB.open ("TestDB", 1) after success / / create data object cn.onupgradeneeded=function (e) {e.target.result.createObjectStore ("Obj");}; / / Database connection succeeded cn.onsuccess=function (e) {main (e.target.result);};}) () Then there are two test pages / / a.html function main (e) {(function callee () {/ / start a transaction e.doTransaction (function (e) {e.put (1, "test"); / / set the value of test to 1 e.put (2, "test"); / / set the value of test to 2}); setTimeout (callee) }) ();}; / / b.html function main (e) {(function callee () {/ / start a transaction e.doTransaction (function (e) {/ / get the value of test e.get ("test") .onsuccess = function (e) {console.log (e.target.result);}); setTimeout (callee) }) ();}
Replace localStorage with indexedDB transaction. But the result is different.
There may not be immediate output in the b.html during testing, because the indexedDB is busy with a.html things, and the b.html transaction is left waiting in the transaction drop queue. But in any case, the output will not be 1. Because the minimum processing unit of indexedDB is the transaction, not the expression unit as localStorage does. This can be achieved simply by putting what needs to be handled between lock and unlock into a transaction. In addition, browsers don't support indexedDB as well as localStorage, so you have to consider browser compatibility when using it.
The above is an example analysis of HTML5's IndexedDB index database. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
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.