HTML5 - IndexedDB

indexeddb เป็นแนวคิด HTML5 ใหม่ในการจัดเก็บข้อมูลภายในเบราว์เซอร์ของผู้ใช้ indexeddb มีพลังงานมากกว่าที่จัดเก็บข้อมูลในตัวเครื่องและมีประโยชน์สำหรับแอปพลิเคชันที่ต้องการจัดเก็บข้อมูลจำนวนมาก แอปพลิเคชันเหล่านี้สามารถทำงานได้อย่างมีประสิทธิภาพมากขึ้นและโหลดได้เร็วขึ้น

ทำไมต้องใช้ indexeddb?

W3C ได้ประกาศว่าฐานข้อมูล Web SQL เป็นข้อกำหนดการจัดเก็บในเครื่องที่เลิกใช้แล้วดังนั้นนักพัฒนาเว็บจึงไม่ควรใช้เทคโนโลยีนี้อีกต่อไป indexeddb เป็นอีกทางเลือกหนึ่งสำหรับฐานข้อมูลเว็บ 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: "[email protected]" },
   { id: "02", name: "Prasad", age: 24, email: "[email protected]" }
];

การเพิ่มข้อมูล

ที่นี่การเพิ่มข้อมูลด้วยตนเองลงในข้อมูลดังที่แสดงด้านล่าง -

function add() {
   var request = db.transaction(["employee"], "readwrite")
   .objectStore("employee")
   .add({ id: "01", name: "prasad", age: 24, email: "[email protected]" });
   
   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!");
      }
   };
}

การลบข้อมูล

เราสามารถลบข้อมูลออกจาก 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: "[email protected]" },
            { id: "00-02", name: "prasad", age: 32, email: "[email protected]" }
         ];
         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: "[email protected]" });
            
            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>

มันจะให้ผลลัพธ์ดังต่อไปนี้ -