Html5-indexeddb

提供:Dev Guides
移動先:案内検索

HTML5-IndexedDB

indexeddbは、ユーザーのブラウザ内にデータを保存するための新しいHTML5コンセプトです。 indexeddbはローカルストレージよりも強力で、大量のデータを保存する必要があるアプリケーションに役立ちます。 これらのアプリケーションは、より効率的に実行し、より高速にロードできます。

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

データを削除する

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: "[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>

それは次の出力を生成します-