返回

IndexedDB:基本使用指南,开启结构化数据存储新篇章

前端

IndexedDB 简介

IndexedDB 是一种低级 API,允许 Web 应用程序在客户端存储大量结构化数据。与 Web Storage(Local Storage 和 Session Storage)不同,IndexedDB 可以存储复杂的数据结构,例如对象和数组。此外,IndexedDB 还可以使用索引来加快数据检索速度,并支持事务以确保数据的一致性。

创建数据库

要使用 IndexedDB,首先需要创建一个数据库。可以使用以下步骤创建数据库:

  1. 打开数据库连接:
var request = indexedDB.open('my_database', 1);
  1. onupgradeneeded 事件中创建对象存储:
request.onupgradeneeded = function(event) {
  var db = event.target.result;

  // 创建一个名为 'customers' 的对象存储
  var objectStore = db.createObjectStore('customers', { keyPath: 'id', autoIncrement: true });

  // 在 'customers' 对象存储中创建索引
  objectStore.createIndex('name', 'name', { unique: false });
  objectStore.createIndex('email', 'email', { unique: true });
};

存储数据

要将数据存储到 IndexedDB,可以使用以下步骤:

  1. 获取对象存储的引用:
var objectStore = db.transaction('customers', 'readwrite').objectStore('customers');
  1. 使用 add() 方法将数据存储到对象存储中:
objectStore.add({ name: 'John Doe', email: 'johndoe@example.com' });

检索数据

要从 IndexedDB 中检索数据,可以使用以下步骤:

  1. 获取对象存储的引用:
var objectStore = db.transaction('customers', 'readonly').objectStore('customers');
  1. 使用 get() 方法获取单个数据项:
objectStore.get(1).then(function(customer) {
  console.log(customer.name); // John Doe
});
  1. 使用 getAll() 方法获取所有数据项:
objectStore.getAll().then(function(customers) {
  console.log(customers); // [{ id: 1, name: 'John Doe', email: 'johndoe@example.com' }, ...]
});
  1. 使用 openCursor() 方法遍历数据项:
objectStore.openCursor().onsuccess = function(event) {
  var cursor = event.target.result;

  if (cursor) {
    console.log(cursor.value.name); // John Doe

    cursor.continue();
  } else {
    // 遍历完成
  }
};

使用事务

事务可以确保一组操作要么全部成功,要么全部失败。要使用事务,可以使用以下步骤:

  1. 创建事务:
var transaction = db.transaction(['customers'], 'readwrite');
  1. 在事务中执行操作:
transaction.objectStore('customers').add({ name: 'Jane Doe', email: 'janedoe@example.com' });
  1. 提交事务:
transaction.commit();

使用游标

游标可以帮助您遍历对象存储中的数据项。要使用游标,可以使用以下步骤:

  1. 获取游标:
var cursor = objectStore.openCursor();
  1. 使用 onsuccess 事件处理程序处理游标:
cursor.onsuccess = function(event) {
  var cursor = event.target.result;

  if (cursor) {
    console.log(cursor.value.name); // John Doe

    cursor.continue();
  } else {
    // 遍历完成
  }
};

使用索引

索引可以加快数据检索速度。要使用索引,可以使用以下步骤:

  1. 创建索引:
objectStore.createIndex('name', 'name', { unique: false });
  1. 使用索引检索数据:
var index = objectStore.index('name');

index.get('John Doe').then(function(customer) {
  console.log(customer.name); // John Doe
});

总结

IndexedDB 是一款功能强大、高性能的本地存储技术,可以帮助您在客户端存储大量结构化数据。通过使用事务、游标和索引,您可以轻松地存储、检索和管理数据。无论您是前端开发者还是后端开发人员,都可以从本指南中学习到 IndexedDB 的基本知识,并将其应用到您的项目中。