indexedDB 批量新增資料

admin發表於2019-07-17

通過物件倉庫的add()方法可以為其新增資料,操作比較簡單。

本文通過一段程式碼例項介紹一下如何批量新增資料,同樣簡單,需要的朋友僅做參考。

程式碼例項如下:

[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(['website'], 'readwrite');
  let objectStore = transaction.objectStore('website');
  for(let i=0;i<students.length;i++){
    objectStore.add(students[i]);
  }
}
</script>
</head>
<body>
  <p>為物件倉庫批量新增資料</p>
</body>
</html>

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

aid[3389]

可以看到通過上述程式碼批量增加了三條資料,下面對程式碼進行一下簡單分析。

(1).開始定義了一組資料儲存在變數students中,非常簡單無需做過多介紹。

(2).window.indexedDB.open("antzone", 1)方法建立或者開啟名為"antzone"的資料庫。

(3).如果已經存在"antzone"資料庫,則將其開啟,否則建立對應名稱資料庫(觸發upgradeneeded事件)。

(4).upgradeneeded事件處理函式首先判斷"students"物件倉庫是否存在,如果不存在則建立。

(5).物件倉庫的主鍵是自增長的,索引名稱是"xingbie",對應的屬性是"sex"。

(6).如果資料庫是新建立並且一切順利,那麼會首先觸發upgradeneeded事件,然後再觸發success事件。

(7).如果資料庫已經存在,且開啟順利,會觸發success事件。

(8).在success事件處理函式中通過迴圈方式遍歷學生資訊,然後將其新增到物件倉庫中。

相關閱讀:

(1).建立於開啟資料庫參閱IndexedDB.open() 開啟與新建資料庫一章節。

(2).建立物件倉庫參閱createObjectStore() 建立物件倉庫一章節。

(3).建立索引參閱IDBObjectStore.createIndex() 索引一章節。

(4).事務參閱IDBTransaction 事務物件一章節。

相關文章