indexedDB 更新資料

admin發表於2019-07-21

實際應用中,我們無意增加資料,而是修改當前已經存在的資料。

本文將通過程式碼例項介紹一下indexedDB資料庫如何更新當前已經存在的資料。

首先通過下面的程式碼批量增加一些資料:

[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',{keyPath:"id"});
    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>indexedDB資料庫批量增加資料</p>
</body>
</html>

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

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

上述程式碼為指定物件倉庫新增了三條資料,下面我們來修改第四條資料。

通過IDBObjectStore.put()方法可以實現更新資料效果,程式碼例項如下:

[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',{keyPath:"id"});
    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 putRequest = objectStore.put({id:1003, name:'螞蟻部落', age:5, email:'ant@163.com'});
  putRequest.onsuccess = function (event) {
    console.log('資料更新成功');
  };

  putRequest.onerror = function (event) {
    console.log('資料更新失敗');
  }
}
</script>
</head>
<body>
  <p>indexedDB資料庫批量增加資料</p>
</body>
</html>

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

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

通過IDBObjectStore.put()方法將第三條資料進行了更新。

關於上述方法的實用方式可以參閱IDBObjectStore.put()方法一章節。

相關文章