HTML - IndexedDB



IndexedDB 是一個新的 HTML5 概念,用於將資料儲存在使用者的瀏覽器中。它比本地儲存更強大,對於需要儲存大量資料的應用程式非常有用。這些應用程式可以執行更高效並載入更快。

為什麼要使用 IndexedDB?

W3C 已宣佈 Web SQL 資料庫是一個已棄用的本地儲存規範,因此 Web 開發人員不應再使用此技術。IndexedDB 是 Web SQL 資料庫的替代方案,並且比舊技術更有效。

特性

  • 它儲存鍵值對

  • 它不是關係資料庫

  • IndexedDB API 主要為非同步的

  • 它不是結構化查詢語言

  • 它允許訪問同一域的資料

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.")
}

開啟 IndexedDB 資料庫

在建立資料庫之前,我們必須為資料庫準備一些資料。讓我們從公司員工詳細資訊開始。

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

新增資料

這裡手動向資料庫中新增一些資料,如下所示:

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! ");
   }
}

檢索資料

我們可以使用 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!");
      }
   };
}

刪除資料

我們可以使用 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 程式碼

要顯示所有資料,我們需要使用 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>
廣告