IndexedDB 是一种底层 API,用于在客户端存储大量的结构化数据(也包括文件/二进制大型对象(blobs))。该 API 使用索引实现对数据的高性能搜索。虽然 Web Storage 在存储较少量的数据很有用,但对于存储更大量的结构化数据来说力不从心。而 IndexedDB 提供了这种场景的解决方案。本页面 MDN IndexedDB 的主要引导页 - 这里,我们提供了完整的 API 参考和使用指南,浏览器支持细节,以及关键概念的一些解释的链接
IndexedDB 是一个基于 JavaScript 的面向对象数据库。IndexedDB 允许您存储和检索用键索引的对象;可以存储结构化克隆算法支持的任何对象。您只需要指定数据库模式,打开与数据库的连接,然后检索和更新一系列事务。
// 初始化数据库
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
if(!window.indexedDB)
{
console.log(“你的浏览器不支持IndexedDB”);
}
var request = window.indexedDB.open(“testDB”, 2); // 打开数据库,parmas:数据库名称及版本号
往ObjectStore里新增对象
var transaction = db.transaction([“students”],”readwrite”);
transaction.oncomplete = function(event) {
console.log(“Success”);
};
transaction.onerror = function(event) {
console.log(“Error”);
};
var objectStore = transaction.objectStore(“students”);
objectStore.add({rollNo: rollNo, name: name});
删除对象
db.transaction([“students”],”readwrite”).objectStore(“students”).delete(rollNo);
通过key取出对象
var request = db.transaction([“students”],”readwrite”).objectStore(“students”).get(rollNo);
request.onsuccess = function(event){
console.log(“Name : “+request.result.name);
};
更行对象
var transaction = db.transaction([“students”],”readwrite”);
var objectStore = transaction.objectStore(“students”);
var request = objectStore.get(rollNo);
request.onsuccess = function(event){
console.log(“Updating : “+request.result.name + “ to “ + name);
request.result.name = name;
objectStore.put(request.result);
};