IndexedDB - 读取数据


我们将数据输入到数据库中,我们需要调用数据来查看变化,也可以用于各种其他目的。

我们必须调用对象存储上的get()方法来读取此数据。get 方法获取要从存储中检索的对象的主键。

句法

var request = objectstore.get(data);

在这里,我们使用 get() 函数请求对象存储来获取数据。

例子

以下示例是请求对象存储获取数据的实现 -

<!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"});
         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: 'abdul', branch: 'IT'}