---
title: IndexedDB:事务与版本升级治理
keywords:
- IndexedDB
- 事务
- 版本升级
- objectStore
- 游标
description: 使用 IndexedDB 管理结构化数据,掌握事务与版本升级模式,处理游标与错误治理,提升一致性与可维护性。
tags:
- IndexedDB
- Web API
- objectStore
- 事务
- 存储
- 游标
- 版本升级
- 稳定性
categories:
- 文章资讯
- 技术教程
---
概述
IndexedDB 提供浏览器端结构化存储与事务模型。通过版本升级创建/迁移对象仓库(objectStore)与索引,使用只读/读写事务进行原子操作。
用法/示例
const req = indexedDB.open('app-db', 3)
req.onupgradeneeded = e => {
const db = e.target.result
if (!db.objectStoreNames.contains('users')) {
const store = db.createObjectStore('users', { keyPath: 'id' })
store.createIndex('by_email', 'email', { unique: true })
}
}
req.onsuccess = () => {
const db = req.result
const tx = db.transaction(['users'], 'readwrite')
const store = tx.objectStore('users')
store.put({ id: 1, email: '[email protected]', name: 'A' })
tx.oncomplete = () => db.close()
}
// 游标遍历
const tx = db.transaction(['users'], 'readonly')
const store = tx.objectStore('users')
store.openCursor().onsuccess = e => {
const cursor = e.target.result
if (cursor) {
// 处理 cursor.value
cursor.continue()
}
}
工程建议
- 在版本升级中进行迁移脚本管理与回滚保护;避免在运行时创建仓库。
- 以事务为边界控制一致性;处理
onabort/onerror并上报失败。 - 对大对象采用分块与引用,结合存储配额与清理策略。
参考与验证
- MDN:IndexedDB — https://developer.mozilla.org/docs/Web/API/IndexedDB_API
- web.dev:IndexedDB — https://web.dev/articles/indexeddb

发表评论 取消回复