IndexedDb -检查表是否存在并包含数据

kmbjn2e3  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(4)|浏览(530)

当我的应用程序第一次运行时,我使用IndexedDB填充了一些数据,我想确保在创建数据库和表时,它们还不存在。
我可以用JavaScript查询表的长度以查看它是否包含和数据吗?

p5fdfcr1

p5fdfcr11#

最好的方法是尝试在try catch块中打开objectStore。它也是同步的。如果出现错误,您可以创建存储,例如:

var store;
  try {
    store = request.transaction.objectStore('yourStore');
  }
  catch(e) {
    store = db.createObjectStore('yourStore');
}
4nkexdtk

4nkexdtk2#

我们可以使用IndexDB的objectStoreNames属性来检查ObjectStore是否存在。

var db_object, object_store;
if( !db.objectStoreNames.contains(currentobjectstore) )
{
  db_object =  i_db.createObjectStore(currentobjectstore, {autoIncrement:true} );
 object_store = db.transaction(currentobjectstore, 'readwrite').objectStore(currentobjectstore);
} else {
 object_store = db.transaction(currentobjectstore, 'readwrite').objectStore(currentobjectstore);
}
6jygbczu

6jygbczu3#

你可以使用objectStore.count()函数,但是我建议你存储一些元数据,这些元数据表明你的本地数据库已经初始化了。否则,你可能会在数据创建的过程中重新加载页面,并且你的数据永远不会与远程数据完全同步。

j1dl9f46

j1dl9f464#

如果不存在具有指定名称的数据库,则创建该数据库,否则将打开该数据库
例如var request = indexedDB.open("DataTbl");
所以如果你的数据库已经存在,它会打开它,然后检查表中的内容是否已经存在,然后你可以创建一个xyz对象存储,并在其中存储一些键/值标志对,说明插入成功,并在以后每次页面重新加载时检查它。
也可以给予at尝试计数函数指定@toske
参考:

相关问题