利用IndexedDB API,可以在客户端构建一个事务性数据库,可以在客户端存储大量的结构化数据。
-
创建并连接到一个IndexedDB数据库
var films= [
{
No: 1,
film_name: "寒战",
director: ["梁乐民", "陆剑青"],
starring: ["郭富城", "梁家辉", "李治廷", "彭于晏", "杨采妮"],
Mins: "98min",
Release_time: "2012-11-08",
synopsis: "该片讲述了在新时代背景下,一辆价值不菲的警察冲锋车被劫持,随之整个香港都陷入到安全危机,警匪之间展开高智商较量。"
},
{
No: 2,
film_name: "踏血寻梅",
director: "翁子光",
starring: ["郭富城","春夏", "白只", "金燕玲"],
Mins: "120min",
Release_time: "2015-04-06",
synopsis: "影片以真实的肢解凶杀案改编,以警察的视点讲一个人性的故事。片中主要的三个人物分别是内地移民少女、失业货车司机及工作狂警察。"
},
{
No: 3,
film_name: "最爱",
director: "顾长卫",
starring: ["章子怡", "郭富城", "陶泽如", "濮存昕", "孙海英", "蒋雯丽"],
Mins: "101min",
Release_time: "2011-05-10",
synopsis: "影片讲述了一个小村庄的村民因为一场突如其来的恶疾而被打乱了平静的生活,人们在恐慌中展现出人性百态。身染绝症的男女主角从相怜、相依到相爱,在这段不被祝福的感情中两人用生命证明了爱情的尊严。"
},
{
No: 4,
film_name: "追凶者也",
director: "曹保平",
starring: ["刘烨", "张译", "段博文", "王子文", "谭卓", "王砚辉", "颜北"],
Mins: "113min",
Release_time: "2016-09-14",
synopsis: "该影片讲述了在偏远的西部村寨悄然发生的一桩残忍凶案,被警方推为首要疑凶的憨包汽修工宋老二与落魄古惑仔王友全、夜总会领班董小凤一起上演了一部嬉笑怒骂的黑色逃杀故事"
},
{
No: 5,
film_name: "硬汉",
director: "丁晟",
starring: ["刘烨", "黄秋生", "孙红雷", "于荣光", "刘洋", "陈雅伦"],
Mins: "95min",
Release_time: "2008-11-28",
synopsis: "讲述一个退伍海军“老三”的故事。讲述的是一个中国式硬汉,塑造了平凡人中的英雄故事。"
}
]
function createDB() {
var db;
//打开数据库
var request = indexedDB.open("filmDB");
//连接数据库失败处理
request.onerror = function (e) {
console.log(e.target.errorCode)
}
//在版本发生变动时会触发upgradeneeded事件。onupgradeneeded 是我们唯一可以修改数据库结构的地方。
//在这里面,我们可以创建和删除对象存储空间以及构建和删除索引
request.onupgradeneeded = function (e) {
db = e.target.result; // 获取数据库对象
//构建一个存储空间
//每一个存入的对象都必须有“No”键。
var objectStore = db.createObjectStore("filmStore", {keyPath: "No"});
//创建索引
//unique: true表示是唯一索引。
//multiEntry: true 表示starring的值如果是个数组,里面的每个数组元素都可作为索引。
objectStore.createIndex("film_name", "film_name", {unique: true});
objectStore.createIndex("director", "director", {unique: false});
objectStore.createIndex("starring", "starring", {multiEntry: true});
objectStore.createIndex("Release_time", "Release_time", {unique: false});
//确保存储空间创建完成后执行
objectStore.transaction.oncomplete = function (e) {
var filmStore = db.transaction("filmStore", "readwrite").objectStore("filmStore");
for (var i = 0, length = films.length; i < length; i++) {
//添加数据到数据库
filmStore.add(films[i]);
}
}
}
}
执行后:
multiEntry属性true/false的对比:
-
从IndexedDB数据库中查找数据
使用keyPath查询:
function getData(storeName, keyPath) {
var result = indexedDB.open("filmDB");
result.onsuccess = function (e) {
var db = e.target.result;
var transaction = db.transaction(storeName, "readonly"); //readonly是默认值,可以不写
var objectStore = transaction.objectStore(storeName);//获取存储空间
var request = objectStore.get(keyPath);返回一个IDBRequest对象
request.onsuccess = function (e) {
console.log(e.target.result.film_name); //result属性保存了与keyPath相关联的数据
}
}
}
getData("filmStore", 3)
输出结果:
使用游标进行条件查找:
//获取2012年以后上映的电影
getRangeData("filmStore","Release_time", IDBKeyRange.lowerBound("2012-01-01"));
function getRangeData(storeName, index, range) { //存储空间名,索引,检索范围
indexedDB.open("filmDB").onsuccess = function (e) {
var db = e.target.result;
var objectStore = db.transaction(storeName).objectStore(storeName).index(index);
objectStore.openCursor(range).onsuccess = function (e) {//使用游标
var cursor = e.target.result;
if (cursor) {
console.log("影片名:" + cursor.value.film_name + " 上映时间:" + cursor.value.Release_time)
cursor.continue(); //游标移动到下一个位置
}
}
}
}
输出结果:
-
更新数据库
给一条数据增加一个项目:
updata({
storeName: "filmStore", //存储空间名
index: "film_name", //索引
value: "硬汉", //检索值
grade: "grade", //增加的键
gradeVal: "R" //增加的键值
})
//通过索引查找数据并更新数据
function updata(obj) {
indexedDB.open("filmDB").onsuccess = function (e) {
var db = e.target.result;
var objectStore = db.transaction(obj.storeName, "readwrite").objectStore(obj.storeName);
var objectStoreIndexResult = objectStore.index(obj.index);
objectStoreIndexResult.get(obj.value).onsuccess = function (e) {
var data = e.target.result;
data[obj.grade] = obj.gradeVal; //添加键值
objectStore.put(data); //更新数据
}
}
}
结果:
使用游标来更新数据:
替换掉整条数据。
function update(obj) {
indexedDB.open("filmDB").onsuccess = function (e) {
var db = e.target.result;
db.transaction(obj.storeName, "readwrite")
.objectStore(obj.storeName)
.index(obj.index)
.openCursor(obj.keyRange)
.onsuccess = function (e) {
var cursor = e.target.result;
if (cursor) {
if (cursor.value.film_name == obj.film_name) {
//把被更新数据的主键值添加到待更新对象上
obj.data.No = cursor.primaryKey;
//替换整个数据
cursor.update(obj.data).onsuccess = function (e) {
console.log("成功")
}
}
cursor.continue();
}
}
}
}
update({
storeName: "filmStore",
index: "film_name",
keyRange:IDBKeyRange.only("追凶者也"),
film_name: "追凶者也",
data: {
film_name: "寒战",
director: ["梁乐民", "陆剑青"],
starring: ["郭富城", "梁家辉", "李治廷", "彭于晏", "杨采妮"],
Mins: "98min",
Release_time: "2012-11-08",
synopsis: "该片讲述了在新时代背景下,一辆价值不菲的警察冲锋车被劫持,随之整个香港都陷入到安全危机,警匪之间展开高智商较量。"
}
})
-
删除IndexedDB数据库中的数据
使用主键删除数据
var request = db.transaction(["filmStore"], "readwrite")
.objectStore("filmStore")
.delete(3);
request.onsuccess = function(event) {
// 删除数据成功!
};
使用游标删除数据
function leleteIndexData(obj) {
indexedDB.open("filmDB").onsuccess = function (e) {
var db = e.target.result;
db.transaction(obj.storeName, "readwrite")
.objectStore(obj.storeName)
.index(obj.index)
.openCursor(obj.keyRange)
.onsuccess = function (e) {
var cursor = e.target.result;
if (cursor) {
cursor.delete().onsuccess = function () {
console.log("成功删除")
}
}
}
}
}
//删除影片名为硬汉的电影数据
leleteIndexData({
storeName: "filmStore",
index: "film_name",
keyRange:IDBKeyRange.only("硬汉")
})
删除整个数据库
indexedDB.deleteDatabase("filmDB");