Indexeddb 简明教程

IndexedDB - Reading Data

我们将数据输入数据库,并且我们需要调用数据以查看更改以及用于其他各种目的。

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

Syntax

var request = objectstore.get(data);

在这里,我们请求 objectstore 使用 get() 函数获取数据。

Example

以下示例是如何实现请求 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"});
         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: 'abdul', branch: 'IT'}