什么是IndexedDB:Web離線數據庫入門簡介及基礎教程

jopen 10年前發布 | 24K 次閱讀 IndexedDB

IndexedDB是什么


簡單來說IndexedDB是HTML5引入的一種可以在Web瀏覽器使用的數據庫,用來持久化大量 數據。它可以讓你的Web應用程序有非常強大的查詢能力,并且可以離線工作。IndexedDB的數據操作直接使用JS腳本,不依賴SQL語句(最初的 Web SQL數據庫己被廢棄),操作返回均采用異步。

下文來自: IndexedDB 規范

客戶端需要存儲大量局部對象,以便滿足Web應用程序對離線數據的要求。 [WEBSTORAGE]可以用來儲存鍵值對(key-value pair)。然而,它無法提供按順序檢索鍵,高性能地按值查詢,或存儲重復的一個鍵。

本規范提供了一些具體的API來實施高級鍵值數據庫,這是最復雜的查詢處理器的核心。它通過傳統數據庫來存儲密鑰和相應的值(每個鍵可以對應多個值),并提供通過確定的順序對值進行遍歷。通常用于插入或刪除的大量數據,以及持久化有序數據結構。

數據庫初始化和創建索引


當創建的library數據庫之前并不存在時,會調用onupgradeneeded接口,在這個函數中可以進行數據庫初始化和創建索引;

這里創建了一個名為"library"的數據庫及一個名為"books"的數據倉庫(ObjectStore相當于表),并填入了一些初始數據。


var db;
var request = indexedDB.open("library");

request.onupgradeneeded = function() {   // 此數據庫此前不存在,進行初始化   var db = request.result;   var store = db.createObjectStore("books", {keyPath: "isbn"});   var titleIndex = store.createIndex("by_title", "title", {unique: true});   var authorIndex = store.createIndex("by_author", "author");

  // 填入初始值   store.put({title: "Quarry Memories", author: "Fred", isbn: 123456});   store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567});   store.put({title: "Bedrock Nights", author: "Barney", isbn: 345678}); };

request.onsuccess = function() {   db = request.result; };</pre>

數據存儲及事務的使用


下面的例子使用事務(transaction)來填入數據:

var tx = db.transaction("books", "readwrite");
var store = tx.objectStore("books");

store.put({title: "Quarry Memories", author: "Fred", isbn: 123456}); store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567}); store.put({title: "Bedrock Nights", author: "Barney", isbn: 345678});

tx.oncomplete = function() {   // All requests have succeeded and the transaction has committed. };</pre>

數據查詢:索引


下面的例子使用索引來查詢其中的一本書。

var tx = db.transaction("books", "readonly");
var store = tx.objectStore("books");
var index = store.index("by_title");

var request = index.get("Bedrock Nights"); request.onsuccess = function() {   var matching = request.result;   if (matching !== undefined) {     // A match was found.     console.log(matching.isbn, matching.title, matching.author);   } else {     // No match was found.     console.log(null);   } };</pre>

數據查詢:索引與游標(cursor)


下面的例子通過索引和游標來來枚舉查詢到的所有匹配的書

var tx = db.transaction("books", "readonly");
var store = tx.objectStore("books");
var index = store.index("by_author");

var request = index.openCursor(IDBKeyRange.only("Fred")); request.onsuccess = function() {   var cursor = request.result;   if (cursor) {     // Called for each matching record.     console.log(cursor.value.isbn, cursor.value.title, cursor.value.author);     cursor.continue();   } else {     // No more matching records.     console.log(null);   } };</pre> 來自:http://ourjs.com/detail/5472db89bc3f9b154e000055

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!