html5文件如何与IndexedDB交互存储 html5文件本地数据库的存取操作

html5文件如何与IndexedDB交互存储 html5文件本地数据库的存取操作
最新回答
时光里

2026-06-26 17:10:24

HTML5文件可通过IndexedDB实现本地数据库的存取操作,具体流程包括初始化数据库、添加数据、读取数据、遍历数据、更新数据及删除数据,以下是详细步骤说明:

  • 一、打开并初始化IndexedDB数据库

    打开数据库:使用window.indexedDB.open(数据库名称, 版本号)请求打开数据库,返回一个IDBOpenDBRequest对象。

    监听升级事件:通过onupgradeneeded事件回调创建对象仓库(Object Store),定义数据结构(如主键字段)。例如:request.onupgradeneeded = (event) => { const db = event.target.result; const store = db.createObjectStore('filesStore', { keyPath: 'id' });};

    获取数据库实例:在onsuccess回调中通过event.target.result获取数据库实例,后续操作需依赖此实例。

  • 二、向IndexedDB中添加数据记录

    开启事务:调用db.transaction(对象仓库名称, 'readwrite')创建读写事务。

    插入数据:从事务中获取对象仓库引用,使用add()或put()方法插入数据。

    add():新增数据,若主键已存在则报错。

    put():新增或更新数据,主键存在时覆盖原有记录。

    监听结果:绑定onsuccess和onerror事件确认操作是否成功。例如:const tx = db.transaction('filesStore', 'readwrite');const store = tx.objectStore('filesStore');store.add({ id: 1, name: 'file1.txt', content: '...' });

  • 三、从IndexedDB读取指定数据

    启动只读事务:使用db.transaction(对象仓库名称, 'readonly')创建只读事务。

    查询数据:调用get(主键值)方法发起请求,在onsuccess回调中通过event.target.result获取数据。若主键不存在,结果为undefined。例如:const tx = db.transaction('filesStore', 'readonly');const store = tx.objectStore('filesStore');const request = store.get(1);request.onsuccess = (event) => { console.log(event.target.result); // 输出查询到的数据};

  • 四、遍历对象仓库中的所有数据

    创建游标请求:使用openCursor()方法遍历对象仓库,返回一个游标对象。

    处理游标数据:在onsuccess回调中检查游标是否为null,若存在则处理当前数据(如读取字段值),并通过cursor.continue()移动到下一条记录。例如:const tx = db.transaction('filesStore', 'readonly');const store = tx.objectStore('filesStore');const request = store.openCursor();request.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { console.log(cursor.value); // 输出当前记录 cursor.continue(); }};

  • 五、更新已存在的数据记录

    开启读写事务:通过db.transaction(对象仓库名称, 'readwrite')创建事务。

    执行更新:使用put()方法传入更新后的完整对象,主键相同即触发更新。例如:const tx = db.transaction('filesStore', 'readwrite');const store = tx.objectStore('filesStore');store.put({ id: 1, name: 'updated.txt', content: 'new content' });

  • 六、删除指定数据或清空对象仓库

    删除单条记录:调用delete(主键值)方法,需在读写事务中执行。

    清空整个仓库:使用clear()方法删除所有记录。

    确认操作结果:通过onsuccess和onerror事件监听删除是否成功。例如:const tx = db.transaction('filesStore', 'readwrite');const store = tx.objectStore('filesStore');store.delete(1); // 删除主键为1的记录// 或 store.clear(); // 清空仓库

注意事项:

  • IndexedDB操作均为异步,需通过事件回调处理结果。
  • 事务模式需根据操作类型选择(只读readonly、读写readwrite)。
  • 游标遍历适合处理大量数据,避免阻塞主线程。
  • 删除操作不可逆,执行前需确认数据是否需要保留。