检查IndexedDB数据库是否存在 [英] Check if IndexedDB database exists
问题描述
是否可以检查IndexedDB数据库是否已存在?当程序尝试打开不存在的数据库时,将创建该数据库. 我能想到的唯一方法是如下所示,在这里测试objectStore是否已经存在,如果不存在,则删除数据库:
Is there a way to check if an IndexedDB database already exists? When a program tries to open a database that does not exists the database is created. The only way that I can think of is something like the following, where I test if an objectStore already exists, if it doesn't, the database is deleted:
var dbexists=false;
var request = window.indexedDB.open("TestDatabase");
request.onupgradeneeded = function(e) {
db = e.target.result;
if (!db.objectStoreNames.contains('todo')) {
db.close();
indexedDB.deleteDatabase("TestDatabase");
} else {
dbexists=true;
}
}
推荐答案
在onupgradeneeded回调中,您可以检查版本. (e.target.result.oldversion).如果 它是0,数据库不存在.
In the onupgradeneeded callback you can check the version. (e.target.result.oldversion). If it is 0, the db didn't exist.
经过一番调查.您不能100%确定是否创建了新的数据库.我确定的一件事是,只有indexeddb的版本为1或更高版本时,您才可以使用它.我相信一个数据库可以存在并具有版本0(唯一的事实是您不能使用它,并且将调用onupgradeneeded事件).
After some investigation. You can't be 100% sure if a new db is created. 1 thing I am sure of is the fact that you can only work with an indexeddb if it has a version 1 or higher. I believe that a db can exist and have a version 0 (The only fact is you can't work with it and the onupgradeneeded event will be called).
我已经建立了自己的indexeddbviewer.在这种情况下,我打开没有版本的indexeddb,如果我进入onupgradeneeded事件,则意味着该数据库不存在.在这种情况下,我将异常终止称为中止",这样它就不会升级到版本1.这是我检查它的方式.
I have build my own indexeddbviewer. In that I open the indexeddb without version and if I come in to the onupgradeneeded event, that means the db doesn't exist. In that case I call the abort so it doesn't upgrade to a version 1. This is the way I check it.
var dbExists = true;
var request = window.indexeddb.open("db");
request.onupgradeneeded = function (e){
e.target.transaction.abort();
dbExists = false;
}
但如上所述.在这种情况下,数据库可能会继续存在,但是onupgradeneeded将始终被调用
but as mentioned. It is possible that the db will continue to exist in that case, but the onupgradeneeded will always be called
这篇关于检查IndexedDB数据库是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!