一、链接数据库
indexedDB没有创建数据库的概念,你可以直接链接数据库,如果你链接的数据库并不存在,那么会自动的创建一个数据库。看下面的这个例子。
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><button type="" id='conbtn'>链接数据库</button><script>// In the following line, you should include the prefixes of implementations you want to test. window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; // DON'T use "var indexedDB = ..." if you're not in a function.
// Moreover, you may need references to some window.IDB* objects: window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange // (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
function connectDB(name,version,success,error){
let dbConnect = indexedDB.open(name,version);
dbConnect.onsuccess = function(e){
console.log('数据库链接成功!');
success(e.target.result);
}
dbConnect.onerror = function(e){
console.log('数据库链接失败!');
error(e);
}
dbConnect.onupgradeneeded = function(e){
success(e.target.result);
let oldVersion = e.oldVersion;
let newVersion = e.newVersion;
console.log('数据库更新成功,旧的版本号为:'+oldVersion+",新的版本号为:"+newVersion);
}
}
window.onload=function(){
let btn = document.getElementById('conbtn');
btn.onclick = function(){
connectDB('haha',1,function(){
console.log('链接成功,或者更新成功回调函数');
},function(){
console.log('链接失败回调函数!')
});
}
}</script></body></html>
查看更多关于将数据库从服务器移到浏览器--indexedDB基本操作封装的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did40820