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.
廣告
© . All rights reserved.