返回

索引数据库使用指南

前端

索引数据库 (IndexedDB) 是一种浏览器 API,允许 Web 应用程序存储大量结构化数据,并以快速且高效的方式检索数据。它提供了一个键值存储模型,其中数据存储在对象存储中,而对象存储又组织成对象存储。

在本文中,我们将深入探讨 IndexedDB 的使用方法,包括如何设置和配置数据库、如何操作对象存储和对象、以及如何管理交易。我们还将提供一些示例代码,以帮助您入门。

设置 IndexedDB

要开始使用 IndexedDB,您需要先获取一个数据库对象。您可以使用以下代码:

var request = indexedDB.open('myDatabase', 1);

其中:

  • 'myDatabase' 是数据库的名称。
  • 1 是数据库的版本号。

如果数据库不存在,则会创建一个新数据库。如果数据库已经存在,则会打开现有数据库。

操作对象存储

对象存储是 IndexedDB 中存储数据的容器。要操作对象存储,您需要先获取一个对象存储对象。您可以使用以下代码:

var objectStore = db.createObjectStore('myObjectStore', { keyPath: 'id' });

其中:

  • 'myObjectStore' 是对象存储的名称。
  • { keyPath: 'id' } 指定对象存储的主键。

操作对象

要向对象存储中添加对象,您可以使用以下代码:

objectStore.add({ id: 1, name: 'John Doe' });

要获取对象存储中的对象,您可以使用以下代码:

objectStore.get(1).then(function(object) {
  console.log(object.name); // John Doe
});

要更新对象存储中的对象,您可以使用以下代码:

objectStore.put({ id: 1, name: 'Jane Doe' });

要从对象存储中删除对象,您可以使用以下代码:

objectStore.delete(1);

管理交易

交易是 IndexedDB 中的一组操作,要么全部成功,要么全部失败。要管理交易,您可以使用以下代码:

var transaction = db.transaction(['myObjectStore'], 'readwrite');

transaction.oncomplete = function(event) {
  console.log('Transaction completed successfully.');
};

transaction.onerror = function(event) {
  console.error('Transaction failed.');
};

var objectStore = transaction.objectStore('myObjectStore');

objectStore.add({ id: 1, name: 'John Doe' });

其中:

  • ['myObjectStore'] 是要进行交易的对象存储的名称数组。
  • 'readwrite' 指定交易类型。

示例代码

以下是一个 IndexedDB 示例代码,它演示了如何创建数据库、对象存储、对象,以及如何管理交易:

var request = indexedDB.open('myDatabase', 1);

request.onsuccess = function(event) {
  var db = event.target.result;

  var objectStore = db.createObjectStore('myObjectStore', { keyPath: 'id' });

  objectStore.add({ id: 1, name: 'John Doe' });

  var transaction = db.transaction(['myObjectStore'], 'readwrite');

  transaction.oncomplete = function(event) {
    console.log('Transaction completed successfully.');
  };

  transaction.onerror = function(event) {
    console.error('Transaction failed.');
  };

  var objectStore = transaction.objectStore('myObjectStore');

  objectStore.get(1).then(function(object) {
    console.log(object.name); // John Doe
  });
};

结论

IndexedDB 是一种强大的 API,可用于存储和检索大量结构化数据。通过遵循本指南中的步骤,您可以轻松入门使用 IndexedDB 并创建高效且可靠的 Web 应用程序。