indexedDB 刪除物件倉庫所有資料

admin發表於2019-07-22

有時候可能需要一次性刪除當前物件倉庫的所有資料。

indexedDB資料庫中的操作非常簡單,通過IDBObjectStore.clear()方法即可實現。

程式碼例項如下:

[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/22/183210quw6gmmusssyg876.jpg\";s:5:\"thumb\";s:0:\"\";s:6:\"remote\";N;}

下面通過IDBObjectStore.clear()方法將其中的資料一次性清空。

上述程式碼改造如下:

[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 clearRequest = objectStore.clear();
  clearRequest.onsuccess=function(){
    console.log("清空成功")
  }
  clearRequest.onsuccess=function(){
    console.log("清空失敗")
  }
}
</script>
</head>
<body>
  <p>為物件倉庫批量新增資料</p>
</body>
</html>

上述程式碼可以清空物件倉庫的所有資料,程式碼執行效果截圖如下:

a:3:{s:3:\"pic\";s:43:\"portal/201907/22/183234f0c0zs8szsm1s0sd.jpg\";s:5:\"thumb\";s:0:\"\";s:6:\"remote\";N;}

上面程式碼已經清空了所有的資料,現在物件倉庫空空如也。

相關文章