什么是IndexedDB:Web离线数据库入门简介及基础教程

jopen 9年前

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);    }  };
来自:http://ourjs.com/detail/5472db89bc3f9b154e000055