当使用 put() 将数据插入到带有 indexeddb 的数据存储中时,有没有办法知道记录是插入还是更新?
我想知道记录是否存在。无论哪种方式,我都会插入/更新数据。异步 api 使这变得困难。
当使用 put() 将数据插入到带有 indexeddb 的数据存储中时,有没有办法知道记录是插入还是更新?
我想知道记录是否存在。无论哪种方式,我都会插入/更新数据。异步 api 使这变得困难。
另一种模式是使用光标。你节省了一点cpu时间。
req = objStore.openCursor(IDBKeyRange.lowerBound(key))
req.onsuccess = function(ev) {
var cursor = ev.target.result;
if (cursor) {
// do update
cursor.continue(next_key);
} else {
// do create
}
};
我在http://lists.w3.org/Archives/Public/public-webapps/2012OctDec/0481.html讨论了这个问题
I don't think you can. You could attempt to do add
first, which would potentially result in a ConstraintError
error. If you get that error, do put
instead.
Or just do a get
first.
Doing get+put always requires two requests. Doing add+put possibly only one (the add).
您可以通过光标更新:
function insertOrUpdateSomething(db, obj) {
var tx = db.transaction('storename','readwrite');
var store = tx.objectStore('storename');
store.openCursor(IDBKeyRange.only(obj.id)).onsuccess = function(event) {
if(event.target.result) {
console.log('Updating %s', JSON.stringify(obj));
event.target.result.update(obj);
} else {
console.log('Inserting %s', JSON.stringify(obj));
event.target.add(obj);
}
};
你可以使用这个功能
SaveOrUpdateDate (db,Table,By,Var,Value,CallbackSuccess, CallbackError){
var data = db.transaction([Table], "readwrite");
var object = data.objectStore(Table);
var index = object.index('by_'+By);
var request = index.get(String(Var));
request.onsuccess = function () {
var result = request.result;
if(typeof result !== 'undefined'){
result[Var] = Value;
}else{
result = new Object();
result[By] = Var;
result[Var] = Value;
}
var request2 = object.put(result);
request2.onsuccess = function(e){
CallbackSuccess();
};
request2.onerror = function(e){
CallbackError();
};
}
}