indexedDB 刪除資料

admin發表於2019-07-21

刪除資料是資料庫最為基本的操作之一,下面通過程式碼例項進行一下介紹。

IDBObjectStore.delete()方法可以實現刪除操作。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script>
let students=[
  { 
    id:1001, 
    name:"張三", 
    age:21,
    sex:"男"
  },{ 
    id:1002, 
    name:"李四", 
    age:20,
    sex:"女"
  },{ 
    id:1003, 
    name:"王五", 
    age:19,
    sex:"女"
  }
];
let request = window.indexedDB.open("antzone", 1);
request.onupgradeneeded = (ev) => {
  let db = ev.target.result;
  if (!db.objectStoreNames.contains('students')) {
    let objectStore = db.createObjectStore('students',{autoIncrement:true});
    objectStore.createIndex("xingbie","sex",{ unique: false });
  }
}
request.onsuccess = (ev) => {
  let db = ev.target.result;
  let transaction = db.transaction(['students'], 'readwrite');
  let objectStore = transaction.objectStore('students');
  for(let i=0;i<students.length;i++){
    objectStore.add(students[i]);
  }
}
</script>
</head>
<body>
  <p>為物件倉庫批量新增資料</p>
</body>
</html>

通過上述程式碼為物件倉庫新增了三條資料,程式碼執行效果截圖如下:

a:3:{s:3:\"pic\";s:43:\"portal/201907/21/220046rqvj33375f23v36j.jpg\";s:5:\"thumb\";s:0:\"\";s:6:\"remote\";N;}

下面通過IDBObjectStore.delete()方法刪除第二條資料,程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script>
let students=[
  { 
    id:1001, 
    name:"張三", 
    age:21,
    sex:"男"
  },{ 
    id:1002, 
    name:"李四", 
    age:20,
    sex:"女"
  },{ 
    id:1003, 
    name:"王五", 
    age:19,
    sex:"女"
  }
];
let request = window.indexedDB.open("antzone", 1);
request.onupgradeneeded = (ev) => {
  let db = ev.target.result;
  if (!db.objectStoreNames.contains('students')) {
    let objectStore = db.createObjectStore('students',{autoIncrement:true});
    objectStore.createIndex("xingbie","sex",{ unique: false });
  }
}
request.onsuccess = (ev) => {
  let db = ev.target.result;
  let transaction = db.transaction(['students'], 'readwrite');
  let objectStore = transaction.objectStore('students');
  let delRequest = objectStore.delete(2);
  
  delRequest.onsuccess = function (event) {
    console.log('資料刪除成功');
  };
  delRequest.onerror = function (event) {
    console.log('資料刪除失敗');
  };
}
</script>
</head>
<body>
  <p>為物件倉庫批量新增資料</p>
</body>
</html>

objectStore.delete()方法的引數是主鍵,上述程式碼可以刪除主鍵為2的資料。

程式碼執行效果截圖如下:

a:3:{s:3:\"pic\";s:43:\"portal/201907/21/220119zdh0ludbihutdhml.jpg\";s:5:\"thumb\";s:0:\"\";s:6:\"remote\";N;}

很多時候我們可以需要批量刪除資料,具體參閱indexedDB 批量刪除資料一章節。

相關文章