IndexedDB - 更新数据
创建数据后,下一步就是对其进行各种操作; 所以我们需要定期更新数据。 当我们将错误的数据输入数据库时,我们还需要更新数据。 在这里,我们必须指定一个读/写事务,因为我们想要写入数据库,而不仅仅是从中读取。
如果我们想要修改它或创建数据库中已存在的条目,我们可以使用 put() 函数。
语法
var requestUpdate = objectStore.put(data);
我们在发生事务的对象存储上使用 put() 函数,并且我们需要更新数据。
示例
让我们看一下下面的脚本,了解如何使用 put() 函数更新或修改 objectstore 中的数据 −
<!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <script> const request = indexedDB.open("botdatabase",1); request.onupgradeneeded = function(){ const db = request.result; const store = db.createObjectStore("bots",{ keyPath: "id"}); } request.onsuccess = function(){ document.write("database opened successfully"); const db = request.result; const transaction=db.transaction("bots","readwrite"); const store = transaction.objectStore("bots"); store.add({id: 1, name: "jason",branch: "IT"}); store.add({id: 2, name: "praneeth",branch: "CSE"}); store.add({id: 3, name: "palli",branch: "EEE"}); store.add({id: 4, name: "abdul",branch: "IT"}); store.put({id: 4, name: "deevana",branch: "CSE"}); const idquery = store.get(4); idquery.onsuccess = function(){ document.write("idquery",idquery.result); } transaction.oncomplete = function(){ db.close; } } </script> </body> </html>
输出
database opened successfully idquery {id: 4, name: 'deevana', branch: 'CSE'} Previously the data stored in id: 4 was Name: abdul Branch : IT But as we updated the entry the values are changed.