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

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;
};

數據存儲及事務的使用

下面的例子使用事務(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.
};

數據查詢:索引

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

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

數據查詢:索引與遊標(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);
}
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章