<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" value="建立物件倉庫和索引" onclick="connectDatabase();">
<input type="button" id="btnSaveData" value="儲存資料" onclick="SaveData()">
<input type="button" id="btnSearchData" value="獲取資料" onclick="getData()">
<input type="button" id="btnUpdateData" value="更新資料" onclick="updateData()">
<input type="button" id="btnDeleteData" value="刪除資料" onclick="deleteData()">
<script>
var db;
var dbName = "HelloTestDatabase";
var dbVersion = 1;
function connectDatabase() {
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
if(!indexedDB) {
alert("你的瀏覽器不支援IndexedDB");
} else {
var request = indexedDB.open(dbName, dbVersion);
request.onerror = function(event) {
alert("Why didn't you allow my web app to use IndexedDB?!");
};
request.onsuccess = function(event) {
console.log("onsuccess");
db = event.target.result;
};
// dbVersion有變動時會觸發這個事件
// 資料的結構的變動需要在這裡面操作
request.onupgradeneeded = function(event) {
console.log("onupgradeneeded");
db = event.target.result;
// 物件倉庫建立部分
// event.target.transaction屬性值為一個IDBTransaction事務物件,此處代表版本更新事務
let tx = event.target.transaction;
let name = 'IMMsg';
// 主鍵設定
let optionalParameters = {
keyPath: 'msgId',
autoIncrement: false
};
// 引數:物件倉庫名, JavasScript物件(可選引數)
let store = db.createObjectStore(name, optionalParameters);
// 索引建立部分
let IndexName = 'usernameIndex'; // 索引名
let keyPath = 'username'; // 索引欄位
let IndexOptionalParameters = {
unique: false,
multiEntry: false
};
let idx = store.createIndex(IndexName, keyPath, IndexOptionalParameters); //引數:索引名
console.log(idx);
// 建立組合索引
idx = store.createIndex('username-otherUsername', ['username','otherUsername']); // corrected
console.log(idx);
console.log('索引建立成功');
};
}
}
function SaveData() {
//開啟讀寫事務
let tx = db.transaction(['IMMsg'],'readwrite');
tx.oncomplete = function(){
console.log('儲存資料成功');
}
tx.onabort = function(){
console.log('儲存資料失敗');
}
let store = tx.objectStore('IMMsg');
let data1 = {
msgId: 1,
username: '張三',
otherUsername: '李四',
senderType: 1, // 1-傳送發, 2-接收方
msgType: 1 ,// 1-文字資訊, 2-圖片, 3-語音
msgContent: '你好',
isRead: 1 // 1-未讀, 2-已讀
};
store.put(data1); // 使用 put 而不是 add 直接更新資料
let data2 = {
msgId: 2,
username: '張三',
otherUsername: '李四',
senderType: 2, // 1-傳送發, 2-接收方
msgType: 1 ,// 1-文字資訊, 2-圖片, 3-語音
msgContent: '我很好',
isRead: 1 // 1-未讀, 2-已讀
};
store.put(data2);
let data3 = {
msgId: 3,
username: '張三',
otherUsername: '李四',
senderType: 1, // 1-傳送發, 2-接收方
msgType: 1 ,// 1-文字資訊, 2-圖片, 3-語音
msgContent: '最近在忙啥',
isRead: 1 // 1-未讀, 2-已讀
};
store.put(data3);
///////////////////////////////////////////////////
let data4 = {
msgId: 4,
username: '李四',
otherUsername: '張三',
senderType: 2, // 1-傳送發, 2-接收方
msgType: 1 ,// 1-文字資訊, 2-圖片, 3-語音
msgContent: '你好',
isRead: 1 // 1-未讀, 2-已讀
};
store.put(data4);
let data5 = {
msgId: 5,
username: '李四',
otherUsername: '張三',
senderType: 1, // 1-傳送發, 2-接收方
msgType: 1 ,// 1-文字資訊, 2-圖片, 3-語音
msgContent: '我很好',
isRead: 1 // 1-未讀, 2-已讀
};
store.put(data5);
let data6 = {
msgId: 6,
username: '張三',
otherUsername: '王麻子',
senderType: 1, // 1-傳送發, 2-接收方
msgType: 1 ,// 1-文字資訊, 2-圖片, 3-語音
msgContent: 'xxxxxx',
isRead: 1 // 1-未讀, 2-已讀
};
store.put(data6);
}
function deleteData() {
var onlyKeyRange = IDBKeyRange.only(["張三","王麻子"]);
var transaction = db.transaction(['IMMsg'], 'readwrite');
var store = transaction.objectStore('IMMsg');
var index = store.index('username-otherUsername');
index.openCursor(onlyKeyRange).onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
store.delete(cursor.value.msgId);
cursor.continue();
} else {
console.log("遍歷完成");
}
};
}
function updateData() {
var onlyKeyRange = IDBKeyRange.only(["張三","李四"]);
var transaction = db.transaction(['IMMsg'], 'readwrite');
var store = transaction.objectStore('IMMsg');
var index = store.index('username-otherUsername');
index.openCursor(onlyKeyRange).onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
cursor.value.isRead = 2;
store.put(cursor.value);
cursor.continue();
} else {
console.log("遍歷完成");
}
};
}
function getData() {
// 1. 遊標遍歷所有資料
// var list = [];
// var objectStore = db.transaction('IMMsg').objectStore('IMMsg');
// objectStore.openCursor().onsuccess = function(event) {
// var cursor = event.target.result;
// if (cursor) {
// list.push(cursor.value);
// cursor.continue();
// } else {
// console.log('Get all data:');
// console.log(list);
// }
// };
//
// 2. 單個索引上使用遊標
// var onlyKeyRange = IDBKeyRange.only("李四");
// var transaction = db.transaction(['IMMsg'], 'readonly');
// var store = transaction.objectStore('IMMsg');
// var index = store.index('usernameIndex');
// var list = [];
// index.openCursor(onlyKeyRange).onsuccess = function(event) {
// var cursor = event.target.result;
// if (cursor) {
// console.log('cursor.value:', cursor.value);
// list.push(cursor.value);
// cursor.continue();
// } else {
// console.log('list:', list);
// }
// };
// 遊標更多用法
// // 匹配所有在 "Bill" 前面的, 包括 "Bill"
// var lowerBoundKeyRange = IDBKeyRange.lowerBound("Bill");
// // 匹配所有在 “Bill” 前面的, 但是不需要包括 "Bill"
// var lowerBoundOpenKeyRange = IDBKeyRange.lowerBound("Bill", true);
// // 匹配所有在'Donna'後面的, 但是不包括"Donna"
// var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true);
// // 匹配所有在"Bill" 和 "Donna" 之間的, 但是不包括 "Donna"
// var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true);
// 3. 組合索引上使用遊標
var onlyKeyRange = IDBKeyRange.only(["張三","李四"]);
var transaction = db.transaction(['IMMsg'], 'readonly');
var store = transaction.objectStore('IMMsg');
var index = store.index('username-otherUsername');
var list = [];
index.openCursor(onlyKeyRange).onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
console.log('cursor.value:', cursor.value);
list.push(cursor.value);
cursor.continue();
} else {
console.log('list:', list);
}
};
}
</script>
</body>
</html>
本作品採用《CC 協議》,轉載必須註明作者和本文連結