Home > Web Front-end > H5 Tutorial > body text

In-depth analysis of HTML5's IndexedDB index database_html5 tutorial skills

WBOY
Release: 2016-05-16 15:46:20
Original
1454 people have browsed it

Introduction
IndexedDB is an HTML5 WEB database that allows HTML5 WEB applications to store data on the user's browser. IndexedDB is very powerful and useful for applications. It can store a large amount of data in the client's chrome, IE, Firefox and other WEB browsers. Here is a brief introduction to the basic concepts of IndexedDB.

What is IndexedDB
IndexedDB, HTML5’s new data storage, can store and operate data on the client, making applications load faster and respond better. It is different from a relational database in that it has data tables and records. It affects the way we design and create applications. IndexedDB creates objects with data types and simple JavaScript persistent objects. Each object can have an index, making it efficient to query and traverse the entire collection. This article gives you a real-life example of how to use IndexedDB in a web application.

Start
We need to include the following pre-code before execution

JavaScript CodeCopy content to clipboard
  1. var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB | | window.msIndexedDB;
  2. //prefixes of window.IDB objects
  3. var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
  4. var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
  5. if (!indexedDB) {
  6. alert("Your browser doesn't support a stable version of IndexedDB.")
  7. }


Open IndexedDB
Before creating the database, we first need to create data for the database. Assume we have the following user information:

JavaScript CodeCopy content to clipboard
  1. var userData = [
  2. { id: "1", name: "Tapas", age: 33, email: "tapas@example.com" },
  3. { id: "2", name: "Bidulata", age: 55, email: "bidu@home.com" }
  4. ];

Now we need to open our database using the open() method:

JavaScript CodeCopy content to clipboard
  1. var db;   
  2. var request = indexedDB.open("databaseName", 1);   
  3.     
  4. request.onerror = function(e) {   
  5. console.log("error: ", e);   
  6. };   
  7.     
  8. request.onsuccess = function(e) {   
  9. db = request.result;   
  10. console.log("success: "  db);   
  11. };   
  12. request.onupgradeneeded = function(e) {   
  13.     
  14. }  

如上所示,我们已经打开了名为"databaseName",指定版本号的数据库,open()方法有两个参数:
1.第一个参数是数据库名称,它会检测名称为"databaseName"的数据库是否已经存在,如果存在则打开它,否则创建新的数据库。
2.第二个参数是数据库的版本,用于用户更新数据库结构。
 
onSuccess处理
发生成功事件时“onSuccess”被触发,如果所有成功的请求都在此处理,我们可以通过赋值给db变量保存请求的结果供以后使用。
 
onerror的处理程序
发生错误事件时“onerror”被触发,如果打开数据库的过程中失败。
 
Onupgradeneeded处理程序
如果你想更新数据库(创建,删除或修改数据库),那么你必须实现onupgradeneeded处理程序,使您可以在数据库中做任何更改。 在“onupgradeneeded”处理程序中是可以改变数据库的结构的唯一地方。
 
创建和添加数据到表:
IndexedDB使用对象存储来存储数据,而不是通过表。 每当一个值存储在对象存储中,它与一个键相关联。 它允许我们创建的任何对象存储索引。 索引允许我们访问存储在对象存储中的值。 下面的代码显示了如何创建对象存储并插入预先准备好的数据:

JavaScript Code复制内容到剪贴板
  1. request.onupgradeneeded = function(event) {   
  2. var objectStore = event.target.result.createObjectStore("users", {keyPath: "id"});   
  3. for (var i in userData) {   
  4. objectStore.add(userData[i]);    
  5. }   
  6. }  

We create an object store using the createObjectStore() method. This method accepts two parameters: - the stored name and the parameter object. Here, we have an object store called "users" and define the keyPath, which is the attribute that makes the object unique. Here, we use "id" as keyPath, this value is unique in the object store, and we have to ensure that the attribute of this "ID" exists in every object in the object store. Once the object store is created, we can start adding data into it using a for loop.

Manually add data to the table:
We can manually add additional data to the database.

JavaScript CodeCopy content to clipboard
  1. function Add() {
  2. var request = db.transaction(["users"], "readwrite").objectStore( "users")
  3. .add({ id: "3", name: "Gautam", age: 30, email: "gautam@store.org" });
  4. request.onsuccess = function(e) {
  5. alert("Gautam has been added to the database.");
  6. };
  7. request.onerror = function(e) {
  8. alert("Unable to add the information.");
  9. }
  10. }

Before we did any CRUD operation (read, write, modify) in the database, we had to use transactions. The transaction() method is used to specify the object storage we want to perform transaction processing. The transaction() method accepts 3 parameters (the second and third are optional). The first is the list of object stores we want to process, the second specifies if we want read only/read-write, and the third is the version change.

Reading data from a table
The get() method is used to retrieve data from object storage. We have previously set the object's id as the keyPath, so the get() method will find an object with the same id value. The following code will return an object we named "Bidulata":

JavaScript CodeCopy content to clipboard
  1. function Read() {   
  2. var objectStore = db.transaction(["users"]).objectStore("users");   
  3. var request = objectStore.get("2");   
  4. request.onerror = function(event) {   
  5. alert("Unable to retrieve data from database!");   
  6. };   
  7. request.onsuccess = function(event) {    
  8. if(request.result) {   
  9. alert("Name: "   request.result.name   ", Age: "   request.result.age   ", Email: "   request.result.email);   
  10. } else {   
  11. alert("Bidulata couldn't be found in your database!");    
  12. }   
  13. };   
  14. }  

 
从表中读取所有数据
下面的方法检索表中的所有数据。 这里我们使用游标来检索对象存储中的所有数据:

JavaScript Code复制内容到剪贴板
  1. function ReadAll() {   
  2. var objectStore = db.transaction("users").objectStore("users");    
  3. var req = objectStore.openCursor();   
  4. req.onsuccess = function(event) {   
  5. db.close();   
  6. var res = event.target.result;   
  7. if (res) {   
  8. alert("Key "   res.key   " is "   res.value.name   ", Age: "   res.value.age   ", Email: "   res.value.email);   
  9. res.continue();   
  10. }   
  11. };   
  12. req.onerror = function (e) {   
  13. console.log("Error Getting: ", e);   
  14. };    
  15. }  

该openCursor()用于遍历数据库中的多个记录。 在continue()函数中继续读取下一条记录。
删除表中的记录
下面的方法从对象中删除记录。

JavaScript Code复制内容到剪贴板
  1. function Remove() {
  2. var request = db.transaction(["users"], "readwrite").objectStore( "users").delete("1");
  3. request.onsuccess = function(event) {
  4. alert("Tapas's entry has been removed from your database.");
  5. };
  6. }

We need to pass the object’s keyPath as a parameter to the delete() method.

Final code
The following method deletes a record from the object source:

JavaScript CodeCopy content to clipboard
  1. >  
  2. <head>  
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  4. <title>IndexedDBtitle>  
  5. <script type="text/javascript">  
  6. var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;   
  7.     
  8. //prefixes of window.IDB objects   
  9. var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;   
  10. var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange   
  11.     
  12. if (!indexedDB) {   
  13. alert("Your browser doesn't support a stable version of IndexedDB.")   
  14. }   
  15. var customerData = [   
  16. { id: "1", name: "Tapas", age: 33, email: "tapas@example.com" },   
  17. { id: "2", name: "Bidulata", age: 55, email: "bidu@home.com" }   
  18. ];   
  19. var db;   
  20. var request = indexedDB.open("newDatabase", 1);   
  21.     
  22. request.onerror = function(e) {   
  23. console.log("error: ", e);   
  24. };   
  25.     
  26. request.onsuccess = function(e) {   
  27. db = request.result;   
  28. console.log("success: "  db);   
  29. };   
  30.     
  31. request.onupgradeneeded = function(event) {   
  32.     
  33. }  
  34. request.onupgradeneeded = function(event) {   
  35. var objectStore = event.target.result.createObjectStore("users", {keyPath: "id"});   
  36. for (var i in userData) {   
  37. objectStore.add(userData[i]);    
  38. }   
  39. }   
  40. function Add() {   
  41. var request = db.transaction(["users"], "readwrite")   
  42. .objectStore("users")   
  43. .add({ id: "3", name: "Gautam", age: 30, email: "gautam@store.org" });   
  44.     
  45. request.onsuccess = function(e) {   
  46. alert("Gautam has been added to the database.");   
  47. };   
  48.     
  49. request.onerror = function(e) {   
  50. alert("Unable to add the information.");    
  51. }   
  52.     
  53. }   
  54. function Read() {   
  55. var objectStore = db.transaction("users").objectStore("users");   
  56. var request = objectStore.get("2");   
  57. request.onerror = function(event) {   
  58. alert("Unable to retrieve data from database!");   
  59. };   
  60. request.onsuccess = function(event) {    
  61. if(request.result) {   
  62. alert("Name: "   request.result.name   ", Age: "   request.result.age   ", Email: "   request.result.email);   
  63. } else {   
  64. alert("Bidulata couldn't be found in your database!");    
  65. }   
  66. };   
  67. }  
  68. function ReadAll() {   
  69. var objectStore = db.transaction("users").objectStore("users");    
  70. var req = objectStore.openCursor();   
  71. req.onsuccess = function(event) {   
  72. db.close();   
  73. var res = event.target.result;   
  74. if (res) {   
  75. alert("Key "   res.key   " is "   res.value.name   ", Age: "   res.value.age   ", Email: "   res.value.email);   
  76. res.continue();   
  77. }   
  78. };   
  79. req.onerror = function (e) {   
  80. console.log("Error Getting: ", e);   
  81. };    
  82. }   
  83. function Remove() {    
  84. var request = db.transaction(["users"], "readwrite").objectStore("users").delete("1");   
  85. request.onsuccess = function(event) {   
  86. alert("Tapas's entry has been removed from your database.");   
  87. };   
  88. }  
  89. script>  
  90. head>  
  91.     
  92. <body>  
  93. <button onclick="Add()">Add recordbutton>  
  94. <button onclick="Remove()">Delete recordbutton>  
  95. <button onclick="Read()">Retrieve single recordbutton>  
  96. <button onclick="ReadAll()">Retrieve all recordsbutton>  
  97. body>  
  98. html>  

localStorage是不带lock功能的。那么要实现前端的数据共享并且需要lock功能那就需要使用其它本储存方式,比如indexedDB。indededDB使用的是事务处理的机制,那实际上就是lock功能。
  做这个测试需要先简单的封装下indexedDB的操作,因为indexedDB的连接比较麻烦,而且两个测试页面都需要用到

JavaScript Code复制内容到剪贴板
  1. //db.js
  2. //Encapsulate transaction operations
  3. IDBDatabase.prototype.doTransaction=function(f){
  4. f(this.transaction(["Obj"],"readwrite").objectStore("Obj"));
  5. };
  6. //Connect to the database and call the main function after success
  7. (function(){
  8. //Open the database
  9. var cn=indexedDB.open("TestDB",1);
  10. //Create data object
  11. cn.onupgradeneeded=function(e){
  12. e.target.result.createObjectStore("Obj");
  13. };
  14. //Database connection successful
  15. cn.onsuccess=function(e){
  16. main(e.target.result);
  17. };
  18. })();
  19. Then there are two test pages
  20. <script src="db. js">script>
  21. <script>
  22. //a.html
  23. function main(e){
  24. (function callee(){
  25. //Start a transaction
  26. e.doTransaction(function(e){
  27. e.put(1,"test"); //Set the value of test to 1
  28. e.put(2,"test"); //Set the value of test to 2
  29. });
  30. setTimeout(callee);
  31. })();
  32. };
  33. script>
  34. <script src="db. js">script>
  35. <script>
  36. //b.html
  37. function main(e){
  38. (function callee(){
  39. //Start a transaction
  40. e.doTransaction(function(e){
  41. //Get the value of test
  42. e.get("test").onsuccess=function(e){
  43. console.log(e.target.result);
  44. };
  45. });
  46. setTimeout(callee);
  47. })();
  48. };
  49. script>

Replace localStorage with indexedDB transaction processing. But the result is different

During the test, there may not be immediate output in b.html because indexedDB is busy processing a.html things, and the b.html transaction is waiting in the transaction queue. But no matter what, the output result will not be the value 1. Because the smallest processing unit of indexedDB is a transaction, not an expression like localStorage. In this way, you only need to put the things that need to be processed between lock and unlock into a transaction. In addition, browser support for indexedDB is not as good as localStorage, so browser compatibility must be considered when using it.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template