Html 简明教程

HTML - IndexedDB

indexedDB 是 HTML5 中一个新的概念,用于存储数据在用户浏览器中。 它比本地存储更强大,而且适用于需要存储大量数据的应用程序。 这些应用程序可以更有效地运行,加载更快。

Why to use indexedDB?

W3C 宣布 Web SQL 数据库是已被弃用本地存储规范,因此 web 开发人员不应该再使用此技术。 IndexedDB 是 web SQL 数据库的一个替代方案,比旧技术更有效。

Features

  1. It stores key-pair values

  2. 它不是一个关系数据库

  3. IndexedDB API 主要是非同步的

  4. 它不是一个结构化查询语言

  5. 它允许从同一域中访问数据

IndexedDB

在进入 IndexedDB 之前,我们需要添加一些实现前缀,如下所示 −

window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange

if (!window.indexedDB) {
   window.alert("Your browser doesn't support a stable version of IndexedDB.")
}

Open an IndexedDB database

在创建数据库之前,我们必须为数据库准备一些数据。让我们从公司员工详细信息开始。

const employeeData = [
   { id: "01", name: "Gopal K Varma", age: 35, email: "contact@tutorialspoint.com" },
   { id: "02", name: "Prasad", age: 24, email: "prasad@tutorialspoint.com" }
];

Adding the data

这里手动将一些数据添加到数据中等,如下所示 −

function add() {
   var request = db.transaction(["employee"], "readwrite")
   .objectStore("employee")
   .add({ id: "01", name: "prasad", age: 24, email: "prasad@tutorialspoint.com" });

   request.onsuccess = function(event) {
      alert("Prasad has been added to your database.");
   };

   request.onerror = function(event) {
      alert("Unable to add data\r\nPrasad is already exist in your database! ");
   }
}

Retrieving Data

我们可以使用 get() 从数据库中检索数据

function read() {
   var transaction = db.transaction(["employee"]);
   var objectStore = transaction.objectStore("employee");
   var request = objectStore.get("00-03");

   request.onerror = function(event) {
      alert("Unable to retrieve daa from database!");
   };

   request.onsuccess = function(event) {
      if(request.result) {
         alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);
      } else {
         alert("Kenny couldn't be found in your database!");
      }
   };
}

使用 get() ,我们可以将数据存储在对象中,而不是将其存储在游标中,我们可以从游标中检索数据

function readAll() {
   var objectStore = db.transaction("employee").objectStore("employee");

   objectStore.openCursor().onsuccess = function(event) {
      var cursor = event.target.result;

      if (cursor) {
         alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
         cursor.continue();
      } else {
         alert("No more entries!");
      }
   };
}

Removing the data

我们可以使用 remove() 方法从 IndexedDB 中删除数据。以下是代码外观 −

function remove() {
   var request = db.transaction(["employee"], "readwrite")
   .objectStore("employee")
   .delete("02");

   request.onsuccess = function(event) {
      alert("prasad entry has been removed from your database.");
   };
}

HTML Code

为了显示所有数据,我们需要使用 onClick 事件,如下面的代码所示 −

<!DOCTYPE html>
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>IndexedDb Demo | onlyWebPro.com</title>
</head>
<body>
   <button onclick="read()">Read </button>
   <button onclick="readAll()"></button>
   <button onclick="add()"></button>
   <button onclick="remove()">Delete </button>
</body>
</html>

最终的代码应该是 −

<!DOCTYPE html>
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <script type="text/javascript">

      //prefixes of implementation that we want to test
      window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

      //prefixes of window.IDB objects
      window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
      window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange

      if (!window.indexedDB) {
         window.alert("Your browser doesn't support a stable version of IndexedDB.")
      }

      const employeeData = [
         { id: "00-01", name: "gopal", age: 35, email: "gopal@tutorialspoint.com" },
         { id: "00-02", name: "prasad", age: 32, email: "prasad@tutorialspoint.com" }
      ];
      var db;
      var request = window.indexedDB.open("newDatabase", 1);

      request.onerror = function(event) {
         console.log("error: ");
      };

      request.onsuccess = function(event) {
         db = request.result;
         console.log("success: "+ db);
      };

      request.onupgradeneeded = function(event) {
         var db = event.target.result;
         var objectStore = db.createObjectStore("employee", {keyPath: "id"});

         for (var i in employeeData) {
            objectStore.add(employeeData[i]);
         }
      }
      function read() {
         var transaction = db.transaction(["employee"]);
         var objectStore = transaction.objectStore("employee");
         var request = objectStore.get("00-03");

         request.onerror = function(event) {
            alert("Unable to retrieve daa from database!");
         };
         request.onsuccess = function(event) {

            // Do something with the request.result!
            if(request.result) {
               alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);
            } else {
               alert("Kenny couldn't be found in your database!");
            }
         };
      }

      function readAll() {
         var objectStore = db.transaction("employee").objectStore("employee");
         objectStore.openCursor().onsuccess = function(event) {
            var cursor = event.target.result;

            if (cursor) {
               alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
               cursor.continue();
            } else {
               alert("No more entries!");
            }
         };
      }

      function add() {
         var request = db.transaction(["employee"], "readwrite")
         .objectStore("employee")
         .add({ id: "00-03", name: "Kenny", age: 19, email: "kenny@planet.org" });

         request.onsuccess = function(event) {
            alert("Kenny has been added to your database.");
         };
         request.onerror = function(event) {
            alert("Unable to add data\r\nKenny is aready exist in your database! ");
         }
      }

      function remove() {
         var request = db.transaction(["employee"], "readwrite")
         .objectStore("employee")
         .delete("00-03");

         request.onsuccess = function(event) {
            alert("Kenny's entry has been removed from your database.");
         };
      }
   </script>
</head>
<body>
   <button onclick="read()">Read </button>
   <button onclick="readAll()">Read all </button>
   <button onclick="add()">Add data </button>
   <button onclick="remove()">Delete data </button>
</body>
</html>