Javascript 如何更新 indexedDB 中的数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11217309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I update data in indexedDB?
提问by Michael
I have tried to get some information from W3Cregarding the update of an objectStore item in a indexedDB database, but with not so much susccess. I found herea way to do it, but it doesn't really work for me.
我试图从W3C获取一些关于 indexedDB 数据库中 objectStore 项目更新的信息,但没有那么成功。我在这里找到了一种方法,但它对我不起作用。
My implementation is something like this
我的实现是这样的
DBM.activitati.edit = function(id, obj, callback){
var transaction = DBM.db.transaction(["activitati"], IDBTransaction.READ_WRITE);
var objectStore = transaction.objectStore("activitati");
var keyRange = IDBKeyRange.only(id);
objCursor = objectStore.openCursor(keyRange);
objCursor.onsuccess = function(e){
var cursor = e.target.result;
console.log(obj);
var request = cursor.update(obj);
request.onsuccess = function(){
callback();
}
request.onerror = function(e){
conosole.log("DBM.activitati.edit -> error " + e);
}
}
objCursor.onerror = function(e){
conosole.log("DBM.activitati.edit -> error " + e);
}
}
I have all DBM.activitati.(add | remove | getAll | getById | getByIndex) methods working, but I can not resolve this.
我的所有 DBM.activitati.(add | remove | getAll | getById | getByIndex) 方法都在工作,但我无法解决这个问题。
If you know how I can manage it, please, do tell!
如果你知道我如何管理它,请告诉我!
Thank you!
谢谢!
回答by buley
Check out this jsfiddlefor some examples on how to update IDB records. I worked on that with another StackOverflower -- it's a pretty decent standalone example of IndexedDB that uses indexes and does updates.
查看此jsfiddle以获取有关如何更新 IDB 记录的一些示例。我与另一个 StackOverflower 一起工作——它是一个相当不错的 IndexedDB 独立示例,它使用索引并进行更新。
The method you seem to be looking for is put, which will either insert or update a record if there are unique indexes. In that example fiddle, it's used like this:
您似乎正在寻找的方法是put,如果有唯一索引,它将插入或更新记录。在那个示例小提琴中,它是这样使用的:
phodaDB.indexedDB.addUser = function(userObject){
//console.log('adding entry: '+entryTxt);
var db = phodaDB.indexedDB.db;
var trans = db.transaction(["userData"],IDBTransaction.READ_WRITE);
var store = trans.objectStore("userData");
var request = store.put(userObject);
request.onsuccess = function(e){
phodaDB.indexedDB.getAllEntries();
};
request.onerror = function(e){
console.log('Error adding: '+e);
};
};
For what it's worth, you've got some possible syntax errors, misspelling "console" in console.logas "conosole".
对于它的价值,您可能会遇到一些语法错误,将“控制台”拼错为“控制台console.log”。
回答by Lutz
A bit late for an answer, but possible it helps others. I still stumbled -as i guess- over the same problem, but it's very simple:
回答有点晚了,但可能对其他人有帮助。我仍然在同一个问题上绊倒了 - 正如我猜想的那样,但这很简单:
If you want to INSERT or UPDATE records you use objectStore.put(object)(help)
If you only want to INSERT records you use objectStore.add(object)(help)
如果你想插入或更新你使用的记录objectStore.put(object)(帮助)
如果你只想插入你使用的记录objectStore.add(object)(帮助)
So if you use add(object), and a record key still exists in DB, it will not overwritten and fires error 0 "ConstraintError: Key already exists in the object store".
If you use put(object), it will be overwritten.
因此,如果您使用add(object), 并且记录键仍然存在于数据库中,它不会被覆盖并触发错误 0“ConstraintError:对象存储中已存在键”。
如果使用put(object),它将被覆盖。
回答by Kevin
I'm a couple of years late, but thought it'd be nice to add my two cents in.
我迟到了几年,但认为加上我的两美分会很好。
First, check out BakedGoodsif you don't want to deal with the complex IndexedDB API.
首先,如果您不想处理复杂的 IndexedDB API ,请查看BakedGoods。
It's a library which establishes a uniform interface that can be used to conduct storage operations in all native, and some non-native client storage facilities. It also maintains the flexibility and options afforded to the user by each. Oh, and it's maintained by yours truly :) .
它是一个库,它建立了一个统一的接口,可用于在所有原生和一些非原生客户端存储设施中进行存储操作。它还保持了每个人为用户提供的灵活性和选项。哦,它真的由你维护 :) 。
With it, placing one or more data items in an object store can be as simple as:
有了它,在对象存储中放置一个或多个数据项可以很简单:
bakedGoods.set({
data: [{key: "key1", value: "value1"}, {key: "key2", value: "value2"}),
storageTypes: ["indexedDB"],
complete: function(byStorageTypeResultDataObj, byStorageTypeErrorObj){}
});
Now to answer the actual question...
现在回答实际问题...
Lets begin by aggregating the valuable information spread across the existing answers:
让我们首先汇总分布在现有答案中的有价值的信息:
IDBObjectStore.put()adds a new record to the store, or updates an existing oneIDBObjectStore.add()adds a new record to the storeIDBCursor.update()updates the record at the current position of the cursor
IDBObjectStore.put()向商店添加新记录,或更新现有记录IDBObjectStore.add()向商店添加新记录IDBCursor.update()更新光标当前位置的记录
As one can see, OP is using an appropriate method to update a record. There are, however, several things in his/her code, unrelated to the method, that are incorrect (with respect to the API today at least). I've identified and corrected them below:
可以看出,OP 正在使用一种适当的方法来更新记录。然而,他/她的代码中有一些与方法无关的东西是不正确的(至少就今天的 API 而言)。我在下面确定并更正了它们:
var cursorRequest = objectStore.openCursor(keyRange); //Correctly define result as request
cursorRequest.onsuccess = function(e){ //Correctly set onsuccess for request
var objCursor = cursorRequest.result; //Get cursor from request
var obj = objCursor.value; //Get value from existing cursor ref
console.log(obj);
var request = objCursor.update(obj);
request.onsuccess = function(){
callback();
}
request.onerror = function(e){
console.log("DBM.activitati.edit -> error " + e); //Use "console" to log :)
}
}
cursorRequest.onerror = function(e){ //Correctly set onerror for request
console.log("DBM.activitati.edit -> error " + e); //Use "console" to log :)
}
回答by le vantard
this is case of update infos of an user object
这是用户对象的更新信息的情况
var transaction = db.transaction(["tab_user"], "readwrite");
var store = transaction.objectStore("tab_user");
var req = store.openCursor();
req.onerror = function(event) {
console.log("case if have an error");
};
req.onsuccess = function(event) {
var cursor = event.target.result;
if(cursor){
if(cursor.value.idUser == users.idUser){//we find by id an user we want to update
var user = {};
user.idUser = users.idUser ;
user.nom = users.nom ;
var res = cursor.update(user);
res.onsuccess = function(e){
console.log("update success!!");
}
res.onerror = function(e){
console.log("update failed!!");
}
}
cursor.continue();
}
else{
console.log("fin mise a jour");
}
}

