通过数据库对象获得事务对象(db.tansaction())
增删改查
1.获取事务对象
指定权限
2.获取你要操作的OS(objecctStore)
3.增删改查
添加数据add()
let ts = DB.transaction(["hero"],"readwrite");
let os = ts.objectStore("hero");
//会返回一个IDBRequest
let request = os.add(data);
request.onsuccess = ()=>{
console.log("添加数据成功")
loadAll();
}
request.onerror = err=>{console.warn(err)}
查询数据
getAll 查询所有数据(ie不支持)
let os = DB.transaction(["hero"],"readwrite").objectStore("hero");
let request = os.getAll();
request.onsuccess = function (){
console.log(this.result);
let ul = ele(".hero_container");
let liStr = "";
this.result.forEach(item=>{
let li = `<li>
<p>名字:<span>${item.name}</span></p>
<p>血量:<span>${item.blood}</span></p>
<p>攻击:<span>${item.att}</span></p>
<P>`;
liStr+=li;
});
ul.innerHTML = liStr;
}
request.onerror = err=>{console.warn(err)}
get查询指定数据
let os = DB.transaction("hero").objectStore("hero");
//指定要查询的索引及对应的内容
let request = os.index("name").get(searchContent);
request.onsuccess = function () {
console.log(this.result);
}
request.onerror = error=>{console.warn(error)}
删除数据
delete
let content = this.children[0].children[0].textContent;
let os = DB.transaction("hero","readwrite").objectStore("hero");
let request = os.delete(content);
request.onsuccess = ()=>{
console.log("删除成功")
loadAll()
}
request.onerror = err=>{console.warn(err)}
clear
let os = DB.transaction("hero","readwrite").objectStore("hero");
let request = os.clear();
os.index("name").get(searchContent);
request.onsuccess = function () {
console.log(this.result);
}
request.onerror = error=>{console.warn(error)}
删除数据
delete
let content = this.children[0].children[0].textContent;
let os = DB.transaction("hero","readwrite").objectStore("hero");
let request = os.delete(content);
request.onsuccess = ()=>{
console.log("删除成功")
loadAll()
}
request.onerror = err=>{console.warn(err)}
clear
let os = DB.transaction("hero","readwrite").objectStore("hero");
let request = os.clear();
request.onsuccess = ()=>{
console.log("清除成功")
loadAll()
}
request.onerror = err=>{console.log(err)}