如何在IndexedDB中创建多个对象存储 [英] How to create multiple object stores in IndexedDB
问题描述
我不知道我是对还是错.但是据我所知,我无法手动创建版本更改事务.调用此方法的唯一方法是在打开索引的数据库连接时更改版本号.如果正确,那么在example1和example2中将永远不会创建新的objectStore吗?
I don't know if I'm right or wrong. But as I know I can't create a version change transaction manually. The only way to invoke this is by changing the version number when opening the indexed DB connection. If this is correct, in example1 and example2 new objectStore will never be created?
Example1
function createObjectStore(name){
var request2 = indexedDB.open("existingDB");
request2.onupgradeneeded = function() {
var db = request2.result;
var store = db.createObjectStore(name);
};
}
Example2
function createObjectStore(name){
var request2 = indexedDB.open("existingDB");
request2.onsuccess = function() {
var db = request2.result;
var store = db.createObjectStore(name);
};
}
Example3-这应该起作用:
Example3 - This should work:
function createObjectStore(name){
var request2 = indexedDB.open("existingDB", 2);
request2.onupgradeneeded = function() {
var db = request2.result;
var store = db.createObjectStore(name);
};
}
如果我想在一个数据库中创建多个objectStore的,如何在打开数据库之前获取/获取数据库版本? 因此,有没有一种方法可以自动完成获取数据库版本号的过程?
If I want to create multiple objectStore's in one database how can I get/fetch database version before opening the database?? So is there a way to automate this process of getting database version number??
除了使用onupgradeneeded事件处理程序之外,是否还有其他方法可以创建objectStore.
Is there any other way to create objectStore other than that using onupgradeneeded event handler.
请帮助.非常感谢.
这是我遇到的相同问题: https://groups.google.com/a /chromium.org/forum/#!topic/chromium-html5/0rfvwVdSlAs
Here is same problem that I have: https://groups.google.com/a/chromium.org/forum/#!topic/chromium-html5/0rfvwVdSlAs
推荐答案
您需要打开数据库以检查其当前版本,然后使用version + 1
再次打开它以触发升级.
You need to open the database to check it's current version and open it again with version + 1
to trigger the upgrade.
这是示例代码:
function CreateObjectStore(dbName, storeName) {
var request = indexedDB.open(dbName);
request.onsuccess = function (e){
var database = e.target.result;
var version = parseInt(database.version);
database.close();
var secondRequest = indexedDB.open(dbName, version+1);
secondRequest.onupgradeneeded = function (e) {
var database = e.target.result;
var objectStore = database.createObjectStore(storeName, {
keyPath: 'id'
});
};
secondRequest.onsuccess = function (e) {
e.target.result.close();
}
}
}
这篇关于如何在IndexedDB中创建多个对象存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!