English 中文(简体)
IndexedDB - Updating Data
  • 时间:2024-11-03

IndexedDB - Updating Data


Previous Page Next Page  

After we created the data, the next step is to perform various operations on it; so we need to update the data regularly. We also need to update the data in the case where we entered data incorrectly into the database. Here, we have to specify a read−write transaction because we want to write to the database, not just read from it.

If we want to modify it or make an entry which is already present in the database we use the put() function.

Syntax


var requestUpdate = objectStore.put(data);

We use the put() function on the object store for which the transaction happened and we need to update data.

Example

Let us look at the script below to understand how to update or modify the data in objectstore using put() function −


<!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: "palp",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>

Output


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.
Advertisements