In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "HTML5's IndexedDB index database instance analysis". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "HTML5's IndexedDB index database instance analysis"!
Introduction
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. Here is a brief introduction to the basic concepts of IndexedDB. What is IndexedDB IndexedDB,HTML5 's new data store, which can be stored and manipulated on the client side, so that applications can be loaded and exchanged for better response. It has a relational database, data tables and indexes. It creates objects of data types and simple JavaScript persistent objects, each of which can be indexed and can effectively query and traverse the entire collection. Here is a real-world example of how to use IndexedDB in a Web application. To begin, we need to include the following code before execution
The JavaScript code copies the content to
Var indexedDB = window .indexedDB | | window.mozIndexedDB | | window.webkitIndexedDB | | window.msIndexedDB
/ / prefix of window.IDB object
Var IDBTransaction = window .IDBTransaction | | window.webkitIDBTransaction | | window.msIDBTransaction
Var IDBKeyRange = window .IDBKeyRange | | window.webkitIDBKeyRange | | window.msIDBKeyRange
If (! IndexedDB) {
Alert ("your browser does not support stable versions of IndexedDB." )
}
: IndexedDB
Before creating a database, we first need to create data for the database, assuming that we have the following user information:
The JavaScript code copies the content to
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:
The JavaScript code copies the content to
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 called "database name" 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 named "database name" already exists, and if so, opens it, otherwise a new database is created. two。 The second parameter is the version of the database, which is used by the user to update the database structure. The "onSuccess" of onSuccess processing 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 "onerror" is triggered when an error event occurs in the handler of onerror, if the process of opening the database fails. Onupgradeneeded handlers 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. Is the only place in the "onupgradeneeded" processor where you can change the structure of the database. Create and add data to tables: IndexedDB uses object storage to store data, not through tables. Index A value is stored in the object store and is associated with a key. It allows us to create any object storage 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:
The JavaScript code copies the content to
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 only object here, we use "id" as the keyPath, this value is unique in the object store, we must make sure that the property of this "ID" exists in every object in the object store. Once we have created the object store, we can start adding data in a loop. Manually add data to the table: we can manually add additional data to the database.
The JavaScript code copies the content to
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 information." )
}
}
The transaction () method specifies the object store that we want to transact. The transaction () method takes three parameters (previously, any CRUD operations we do in the database (read, write, modify) must use transactions. 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 replace / read, and the third is the version change. The get () method that reads data from a table 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":
The JavaScript code copies the content to
Function Read () {
Var objectStore = db. Transaction (["users"]). ObjectStore ("users")
Var request = objectStore .get ("2")
Request.onerror = function (event) {
Alert ("unable to retrieve data from the database!" )
}
Request.onsuccess = function (event) {
If (request.result) {
Alert ("name:" + request.result.name + ", age:" + request.result.age + ", email:" + request.result.email)
} other {
Alert ("Bidulata not 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:
The JavaScript code copies the content to
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 acquisition:", e)
}
}
The openCursor () is used to traverse multiple records in the database. Continue to read the next record in the continue () function. Delete the record in the table the following method deletes the record from the object.
The JavaScript code copies the content to
Function Remove () {
Var request = db .transaction (["users"], "readwrite"). ObjectStore ("users"). Delete ("1")
Request.onsuccess = function (event) {
Alert ("the entry for Tapas has been deleted from your database." )
}
}
We pass the object's keyPath as a parameter to the delete () method. The following method in the final code deletes a record from the object source:
The JavaScript code copies the content to
< meta http-equiv = " Content-Type" content = " text / html; charset = utf-8" /> < title >IndexedDB
Var indexedDB = window .indexedDB | | window.mozIndexedDB | | window.webkitIndexedDB | | window.msIndexedDB
/ / prefix of window.IDB object
Var IDBTransaction = window .IDBTransaction | | window.webkitIDBTransaction | | window.msIDBTransaction
Var IDBKeyRange = window .IDBKeyRange | | window.webkitIDBKeyRange | | window.msIDBKeyRange
If (! IndexedDB) {
Alert ("your browser does not support stable versions 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 ("user")
.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 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 the database!" )
}
Request.onsuccess = function (event) {
If (request.result) {
Alert ("name:" + request.result.name + ", age:" + request.result.age + ", email:" + request.result.email)
} other {
Alert ("Bidulata not 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 acquisition:", e)
}
}
Function Remove () {
Var request = db .transaction (["users"], "readwrite"). ObjectStore ("users"). Delete ("1")
Request.onsuccess = function (event) {
Alert ("the entry for Tapas has been deleted from your database." )
}
}
< button onclick = " Add()" >Add record
< button onclick = " Remove()" >Delete record
< button onclick = " Read()" >Retrieve a single record
< button onclick = " ReadAll()" >Retrieve all records
Lock
LocalStorage does not have a lock function. Then in order to achieve the front-end data sharing and need lock function, we need to use other storage methods, index indexDB. IndededDB uses a transaction mechanism, which is actually the locking 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
The JavaScript code copies the content to
/ / db.js
/ / encapsulate transaction operations
IDBDatabase.prototype.doTransaction = function (f) {
F (this.transaction (["Obj"], "readwrite"). ObjectStore ("Obj"))
}
/ / Connect to the database, and call the main function after success
(function () {
/ / Open the database
Var cn = indexedDB .open ("TestDB", 1)
/ / create a data object
Cn.onupgradeneeded = function (e) {
E.target.result.createObjectStore ("Obj")
}
/ / Database connection succeeded
Cn.onsuccess = function (e) {
Main (e.target.result)
}
) ()
Next 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 1
E.put (2, "test"); / / set the value of test 2
})
SetTimeout (callee)
) ()
}
/ / b.html
Function main (e) {
(function callee () {
/ / start a transaction
E.doTransaction (function (e) {
/ / get the value of the test
E.get ("test"). Onsuccess = function (e) {
Console.log (e.target.result)
}
})
SetTimeout (callee)
) ()
}
Replace local storage with indexedDB transactions. But the result is different.
There may not be immediate output in the b.html during the test, because indexedDB is busy with a.html things, and the b.html transaction lost the transaction and was waiting. But in any case, the output will not be 1. Because the minimum processing unit of indexedDB is the transaction, not the localStorage, which is in terms of expressions. This can be achieved as long as what needs to be handled between the lock and unlock is put into a transaction. In addition, browsers don't support indexedDB as well as localStorage, so you have to consider browser compatibility when using it.
At this point, I believe that everyone on the "HTML5 IndexedDB index database instance analysis" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.