IndexedDB通过事务保障数据操作的原子性与一致性,所有操作必须在事务中进行;事务由db.transaction()创建,分readonly、readwrite、versionchange三种模式,作用域限定于指定对象仓库。

IndexedDB 通过事务(transaction)来保障数据操作的原子性与一致性,所有增删改查都必须在事务中进行,不能直接操作数据库。
事务的创建与作用域
事务由 db.transaction() 创建,需指定目标对象仓库名(或数组)和可选模式:
-
只读事务:
"readonly"—— 仅允许get()、count()、openCursor()等读操作 -
读写事务:
"readwrite"—— 支持add()、put()、delete()、clear()等写操作 -
版本变更事务:
"versionchange"—— 仅在onupgradeneeded中自动触发,用于建库/改结构,不可手动创建
事务作用域限定于指定的对象仓库,跨仓库操作需显式列出多个名称(如 ["users", "posts"])。
添加与更新数据(put)
put() 是最常用的写入方法,支持插入新记录或按主键更新已有记录:
立即学习“前端免费学习笔记(深入)”;
const tx = db.transaction("users", "readwrite");
const store = tx.objectStore("users");
// 插入或更新一条用户记录(主键为 id)
store.put({ id: 1, name: "张三", email: "zhang@example.com" });
// 可监听事务完成或失败
tx.oncomplete = () => console.log("保存成功");
tx.onerror = () => console.error("事务出错:", tx.error);
注意:add() 与 put() 区别在于,add() 遇到重复主键会报 ConstraintError,而 put() 会静默覆盖。
查询单条与多条数据(get / getAll)
读操作必须在 "readonly" 或 "readwrite" 事务中进行:
-
get(key):根据主键精确查询单条 -
getAll():获取全部记录(可配合query参数做范围查询) -
openCursor():适合遍历、分页或条件筛选(如用IDBKeyRange.bound())
示例:
const tx = db.transaction("users", "readonly");
const store = tx.objectStore("users");
// 查询 id=1 的用户
store.get(1).onsuccess = function(e) {
console.log("查到:", e.target.result); // {id: 1, name: "张三", ...}
};
// 查询 name 以 "张" 开头的用户(需 name 字段已建索引)
const index = store.index("nameIndex");
index.getAll(IDBKeyRange.bound("张", "张\uFFFF")).onsuccess = function(e) {
console.log("匹配用户:", e.target.result);
};
删除与清空数据(delete / clear)
删除操作同样依赖事务和对象仓库上下文:
-
delete(key):按主键删除单条 -
delete(query):支持IDBKeyRange删除范围(如时间区间) -
clear():清空整个对象仓库(慎用)
示例:
const tx = db.transaction("users", "readwrite");
const store = tx.objectStore("users");
// 删除主键为 1 的记录
store.delete(1);
// 删除所有邮箱包含 "@test.com" 的用户(需先在 email 字段建索引)
const emailIndex = store.index("emailIndex");
emailIndex.openCursor(IDBKeyRange.only("@test.com")).onsuccess = function(e) {
const cursor = e.target.result;
if (cursor) {
cursor.delete(); // 在游标上直接删
cursor.continue();
}
};
事务会自动提交——只要没抛异常且所有请求完成,就视为成功;任意请求失败或未捕获异常会导致事务回滚。不复杂但容易忽略。



















