IndexedDB 建立資料庫時使用自增的Key 更新資料庫遇到的問題的一點記錄

grantgrant發表於2024-04-29
開始時是這個樣子建立的資料庫,更新總報錯:
// 建立儲存庫
objectStore = db.createObjectStore(storeName, {
autoIncrement: true // 實現自增
});
後來改成這樣建立, 更新終於成功了!:
// 建立儲存庫
objectStore = db.createObjectStore(storeName, {
keyPath:'primaryKeyName',
autoIncrement: true // 實現自增
});
按照自增KEY更新資料庫的函式:
function updateDB(db, storeName, data,key) {
var request = db
.transaction([storeName], "readwrite") // 事務物件
.objectStore(storeName) // 倉庫物件
.put(data,key);

request.onsuccess = function () {
console.log("資料更新成功");
};

request.onerror = function () {
console.log("資料更新失敗");
};
}
呼叫函式更新資料庫:
openDB(dbname, 1).then((db) => {
db = db
var date = new Date()
var now = date.toLocaleDateString()
var data = {
content:text,
clickcontent:clickedText,
date:now
}
updateDB(db, storename, data,key)
})

相關文章