更新版本时如何清除 indexedDB 中的所有数据?
How clear all data from indexedDB when update version?
我有两个问题:
1. 我想在更新我的数据库版本时清除所有数据。
objectStore.clear();
但是我有错误:
main1.js:42 未捕获的约束错误:无法在 'IDBDatabase' 上执行 'createObjectStore':具有指定名称的对象存储已存在。
当更新版本数据库只向我的数据库添加新项目时如何?
var browserDatabase={};
browserDatabase._db = null;
browserDatabase._dbVersion = 4;
browserDatabase._dbName = "mediaStorageDB";
browserDatabase._storeName = "myStore";
var idb = window.indexedDB
var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction;
var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;
var dbName='nameDb';
if (!window.indexedDB) {
// window.alert("Ваш браузер не поддерживат стабильную версию IndexedDB. Такие-то функции будут недоступны");
}
var request = window.indexedDB.open("MyTestDatabase", 7);
request.onupgradeneeded = function(e) {
console.log( e.oldVersion )
db = event.target.result;
//console.log(db)
// Создаем хранилище объектов для этой базы данных
// var objectStore = db.createObjectStore("name", { keyPath: "myKey" })
const customerData = [
{ ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" },
{ ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" }
];
var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
// Create an index to search customers by name. We may have duplicates
// so we can't use a unique index.
objectStore.createIndex("name", "name", { unique: false });
// Create an index to search customers by email. We want to ensure that
// no two customers have the same email, so use a unique index.
objectStore.createIndex("email", "email", { unique: true });
objectStore.clear(); //clear previous version
// Store values in the newly created objectStore.
for (var i in customerData) {
objectStore.add(customerData[i]);
}
if (e.oldVersion < 1) {
// create v1 schema
}
if (e.oldVersion < 2) {
// upgrade v1 to v2 schema
}
if (e.oldVersion < 3) {
// upgrade v2 to v3 schema
}
// ...
};
request.onerror = function(event) {
// Сделать что-то при ошибке request.errorCode!
console.log('error');
console.log(event);
};
request.onsuccess = function(event) {
// Выполнить какой-то код если запрос успешный request.result!
console.log('success');
db = event.target.result;
console.log(db);
var transaction = db.transaction(["customers"], "readwrite");
const customerData = [
{ ssn: "888-44-4444", name: "Sasga", age: 35, email: "sasha@company.com" },
{ ssn: "99-55-5555", name: "Andrii", age: 32, email: "andrii@home.org" }
];
var objectStore = transaction.objectStore("customers");
for (var i in customerData) {
var request = objectStore.add(customerData[i]);
request.onsuccess = function(event) {
// event.target.result == customerData[i].ssn;
};
}
transaction.oncomplete = function(event) {
console.log("All done!");
};
transaction.onerror = function(event) {
// Don't forget to handle errors!
};
};
clear
将删除商店中的所有数据。
deleteObjectStore
将删除商店。
您收到错误消息,因为商店已经存在并且您正在尝试创建它。如果你想能够运行create
,你必须先deleteObjectStore
。
然而,这可能不是您最终想要做的。在版本更改中,您通常不想删除对象存储、索引和数据。你只想更新它们。
我有两个问题: 1. 我想在更新我的数据库版本时清除所有数据。
objectStore.clear();
但是我有错误: main1.js:42 未捕获的约束错误:无法在 'IDBDatabase' 上执行 'createObjectStore':具有指定名称的对象存储已存在。
当更新版本数据库只向我的数据库添加新项目时如何?
var browserDatabase={};
browserDatabase._db = null; browserDatabase._dbVersion = 4; browserDatabase._dbName = "mediaStorageDB"; browserDatabase._storeName = "myStore"; var idb = window.indexedDB var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction; var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange; var dbName='nameDb'; if (!window.indexedDB) { // window.alert("Ваш браузер не поддерживат стабильную версию IndexedDB. Такие-то функции будут недоступны"); } var request = window.indexedDB.open("MyTestDatabase", 7); request.onupgradeneeded = function(e) { console.log( e.oldVersion ) db = event.target.result; //console.log(db) // Создаем хранилище объектов для этой базы данных // var objectStore = db.createObjectStore("name", { keyPath: "myKey" }) const customerData = [ { ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" }, { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" } ]; var objectStore = db.createObjectStore("customers", { keyPath: "ssn" }); // Create an index to search customers by name. We may have duplicates // so we can't use a unique index. objectStore.createIndex("name", "name", { unique: false }); // Create an index to search customers by email. We want to ensure that // no two customers have the same email, so use a unique index. objectStore.createIndex("email", "email", { unique: true }); objectStore.clear(); //clear previous version // Store values in the newly created objectStore. for (var i in customerData) { objectStore.add(customerData[i]); } if (e.oldVersion < 1) { // create v1 schema } if (e.oldVersion < 2) { // upgrade v1 to v2 schema } if (e.oldVersion < 3) { // upgrade v2 to v3 schema } // ... }; request.onerror = function(event) { // Сделать что-то при ошибке request.errorCode! console.log('error'); console.log(event); }; request.onsuccess = function(event) { // Выполнить какой-то код если запрос успешный request.result! console.log('success'); db = event.target.result; console.log(db); var transaction = db.transaction(["customers"], "readwrite"); const customerData = [ { ssn: "888-44-4444", name: "Sasga", age: 35, email: "sasha@company.com" }, { ssn: "99-55-5555", name: "Andrii", age: 32, email: "andrii@home.org" } ]; var objectStore = transaction.objectStore("customers"); for (var i in customerData) { var request = objectStore.add(customerData[i]); request.onsuccess = function(event) { // event.target.result == customerData[i].ssn; }; } transaction.oncomplete = function(event) { console.log("All done!"); }; transaction.onerror = function(event) { // Don't forget to handle errors! }; };
clear
将删除商店中的所有数据。
deleteObjectStore
将删除商店。
您收到错误消息,因为商店已经存在并且您正在尝试创建它。如果你想能够运行create
,你必须先deleteObjectStore
。
然而,这可能不是您最终想要做的。在版本更改中,您通常不想删除对象存储、索引和数据。你只想更新它们。