浏览器结构化数据存储方案—IndexedDB 讲解

1,168 阅读3分钟

这是我参与8月更文挑战的第20天,活动详情查看:8月更文挑战

想必在使用一些浏览器存储方案,例如 storage 或者 cookies 的时候,你肯定看到了还有一个叫 IndexedDB 的东西,它是 HTML5 规范里新增的一个浏览器内置数据库,与其他存储不同的是,IndexedDB 可以提供类似数据库风格的存储和使用方式。 我们知道 sessionStorage 和 cookie 都不是持久化的存储,而 localStorage 又有一定大小限制,因此 IndexedDB 的出现很大的弥补了其它方案的不足,不仅可以存储大型数据,而且在 online 和 offline 模式下都能使用。

使用 IndexedDB 的场景

很显然在对于有大型数据存储的 web 应用,IndexedDB 是首选的浏览器存储方案,它的 API 是异步调用的,使用索引存储数据,所有的数据库操作都在事务中进行。 而像 localStorage 比较适用于简单数据的存储,它是用键值对的形式存储数据,所以对于简单数据的数据,还是要优先选择 localStorage,对于大量数据处理的操作,IndexedDB 会更加合适。

浏览器支持

判断当前浏览器环境是否支持 IndexedDB,可以使用以下代码,示例:

window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

if(!window.indexedDB){
    console.log("你的浏览器不支持IndexedDB");
}

基础使用方法

打开一个数据库

使用一个 IndexedDB 数据库需要先打开这个数据库,用到.open方法,该方法接收两个参数,一个是数据库名,一个是数据库版本。示例:

var db;
let request = window.indexedDB.open('databaseName');

request.onerror = event => {
    console.log("打开本地indexedDB存储失败")
}

request.onsucess = event => {
	db = event.target.result;
}

如果这个名为databaseName的数据库不存在,则会自动创建,同时会触发onupgradneeded事件。 在有些浏览器中,首次使用 IndexedDB 存储时浏览器会给用户提醒,用户可以选择允许访问或者拒绝访问。在浏览器的隐私模式下 IndexedDB 是被完全禁止的。

数据操作

对数据的操作需要在事务的基础之上,并且需要有读写权限。示例:

// 创建事务,模式为 readwrite
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);
更新数据
var transaction = db.transaction(["students"],"readwrite");
var objectStore = transaction.objectStore("students");
var request = objectStore.get(rollNo);
request.onsuccess = function(event){
	request.result.name = name;
    objectStore.put(request.result);
};

事务的三种模式

  • versionchange: 修改数据库模型或者接口,包括新建或者删除对象仓库或者索引
  • readonly: 只读
  • readwrite: 读写

欢迎阅读其它文章