如何在事务中创建索引数据库存储

How to create IndexedDb stores in a transaction?

本文关键字:索引 数据库 存储 创建 事务      更新时间:2023-09-26

我是第一次创建本地 IndexedDB,浏览器触发onupgradeneeded请求以响应window.indexedDB.open方法。

我想在onupgradeneeded事件中创建多个表(例如商店),但我想在事务中创建。

我看到事务对象支持".objectStore",但这意味着已经创建了存储/表。

如何创建多个商店并将其包装在交易中?

要在升级中创建多个对象存储,请执行以下操作:

var request = indexedDB.open(...);
request.onupgradeneeded = function(event) {
  // side note: this === request === event.target === event.currentTarget
  var db = this.result;
  // Create 0 or more object stores here using this one instance of IDBDatabase.
  db.createObjectStore(...);
  db.createObjectStore(...);
  ...
};

onupgradeneed事件在类型为VERSION_CHANGE的IDBRequest对象中创建隐式事务。该事务适用于 onupgradeRequired 回调中的所有调用。上面的每个 createObjectStore 调用都隐式使用相同的事务。

如果需要,可以在此函数中获取对此事务使用this.transaction的引用。在这里,您正在访问打开请求的隐式生成的事务属性,该属性引用为您创建的 IDBTransaction 对象(类型设置为 VERSION_CHANGE),这与使用 IDBDatabase.prototype.transaction 方法显式创建事务明显不同。

您可以在onupgradeneeded事件处理程序中创建多个对象存储。它已经在交易中。实际上,它是数据库上的全局独占事务。

创建

所需的对象存储及其索引后,可以在数据库连接上创建事务。你只需要在db.transaction中传递对象存储列表。

您可以使用事务onupgradeneeded,但最好仅用于在那里创建对象存储。在完成事件后创建另一个用于读取和写入onupgradeneeded事务。

在浏览器的控制台中运行此 IndexedDB 事务示例

let db;
dbName = "Jokes";
dbVersion = 5;
const request = indexedDB.open(dbName, dbVersion);
request.onupgradeneeded = e => {
    db = e.target.result
    console.log(db);
    const jstore = db.createObjectStore("JokeStore", { keyPath: "title" });
    const mstore = db.createObjectStore("MockStore", { keyPath: "title" });
    alert("upgrade");
}
request.onsuccess = e => {
    db = e.target.result
    console.log(db);
    alert("success");
}
request.onerror = e => {
    alert("error" + e.target.error);
}
const tx = db.transaction("JokeStore", "readwrite");
tx.onerror = e => alert(e.target.error);
const jstoretx = tx.objectStore("JokeStore");
jstoretx.add({ title: "Knock Knock", text: "Who's there? There is a place." });

它在数据库存储中创建一个条目。