ホームページ >ウェブフロントエンド >htmlチュートリアル >html5のクライアント側データベースストレージにindexeddbを使用するにはどうすればよいですか?
indexedDBは、ファイル/ブロブを含む構造化データのクライアント側ストレージの低レベルAPIです。クライアント側のデータベースストレージにhtml5でindexedDBを使用するには、次の手順に従うことができます。
データベースを開きます:
IndexEdDBデータベースへの接続を開くことから始めます。これはindexedDB.open()
メソッドを使用して実行できます。データベースの名前とオプションでバージョン番号を指定します。 onupgradeneeded
Event Handlerは、データベースの作成時またはそのバージョンの変更時にデータベーススキーマをセットアップするために使用されます。
<code class="javascript">const request = indexedDB.open("MyDatabase", 1); request.onupgradeneeded = function(event) { const db = event.target.result; // Create an objectStore for this database const objectStore = db.createObjectStore("items", { keyPath: "id" }); // Create an index to search items by name objectStore.createIndex("name", "name", { unique: false }); };</code>
データの追加:
IndexEdDBデータベースにデータを追加するには、最初にトランザクションを開き、次にオブジェクトストアでadd()
またはput()
メソッドを使用します。
<code class="javascript">request.onsuccess = function(event) { const db = event.target.result; const transaction = db.transaction(["items"], "readwrite"); const objectStore = transaction.objectStore("items"); const request = objectStore.add({ id: 1, name: "item1", price: 10 }); request.onsuccess = function(event) { console.log("Item added to the database"); }; };</code>
データを取得:
データを取得するには、キーを知っている場合はget()
メソッドを使用できます。より複雑なクエリには、カーソルまたはインデックスを使用できます。
<code class="javascript">request.onsuccess = function(event) { const db = event.target.result; const transaction = db.transaction(["items"], "readonly"); const objectStore = transaction.objectStore("items"); const request = objectStore.get(1); request.onsuccess = function(event) { console.log("Item retrieved: ", event.target.result); }; };</code>
データを更新および削除します:
データの更新は、キーに基づいてデータを挿入または更新するput()
メソッドを使用して実行できます。データを削除するには、 delete()
メソッドを使用します。
<code class="javascript">request.onsuccess = function(event) { const db = event.target.result; const transaction = db.transaction(["items"], "readwrite"); const objectStore = transaction.objectStore("items"); const requestUpdate = objectStore.put({ id: 1, name: "item1 updated", price: 15 }); const requestDelete = objectStore.delete(2); };</code>
エラー処理:
onerror
イベントを使用して常にエラーを処理して、データベース操作中に発生する問題をキャッチします。
<code class="javascript">request.onerror = function(event) { console.log("Database error: " event.target.errorCode); };</code>
indexedDBは、クライアント側にデータを保存するためのいくつかの利点を提供します。
IndexEdDBのデータの持続性とセキュリティを確保するには、いくつかの重要なプラクティスが含まれます。
データの持続性:
データセキュリティ:
indexedDBを実装する場合、パフォーマンスの問題やアプリケーションの障害につながる可能性のある一般的な落とし穴を避けることが重要です。
onerror
イベントハンドラーを常に使用して、エラーをキャッチおよびログにしてください。idb
などのポリフィルまたはライブラリを使用してブラウザの違いを抽象化することを検討してください。以上がhtml5のクライアント側データベースストレージにindexeddbを使用するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。