Indexeddb 简明教程

IndexedDB - Deleting Data

在许多情况下,我们需要从数据库中删除数据,无论是出于存储目的,还是只是为了删除不想保留的数据以释放空间。如果我们希望从数据库中删除此不必要的数据,则可以使用 .delete() 函数。

Syntax

const request = objectStore.delete(data);

我们使用 delete() 函数删除不需要的数据库字段。

Example

我们来看一个用于删除数据的示例脚本 −

<!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 deletename = store.delete(1);
         deletename.onsuccess = function(){
            document.write("id : 1 has been deleted");
         }
         transaction.oncomplete = function(){
            db.close;
         }
      }
   </script>
</body>
</html>

Output

database opened successfully
id : 1 has been deleted

删除 id:1 之后的数据库 =

0  2
{id: 2, name: 'praneeth', branch: 'CSE'}
1  3
{id: 3, name: 'palli', branch: 'EEE'}
2  4
{id: 4, name: 'deevana', branch: 'CSE'}