1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| <script> //连接数据库,版本号可不写 var request = window.indexedDB.open("mydb",6);
const personData = [ { id:"5",name:"asdf",value:"ccc" }, { id:"6",name:"asdfasdf",value:"ccdsc" } ]; //如果数据库打开成功 var mydb; request.onsuccess = function(event){ console.log('数据库打开成功'); mydb = event.target.result; //这个对象很重要,大概所有的操作都要通过该对象进行 var objSto = mydb.transaction("person","readwrite").objectStore("person"); //删除请求,参数指定的是主键的值 var deleterequest = objSto.delete("5"); deleterequest.onsuccess = function(event){ console.log("数据删除成功"); }; /* 这里是添加数据模块,由于某行数据重复添加会出现错误导致后面的全部操作事务全部失败,故注释了 var addrequest = objSto.add({ id:"8",name:"asdfasdf",value:"ccdsc" }); addrequest.onsuccess = function(event){ console.log("add success!"); }; addrequest.onerror = function(event){ console.log("add failed!"); }; */
//查询模块 var findrequest = objSto.get("2"); findrequest.onsuccess = function(event){ console.log("success find") if(findrequest.result){ console.log("name:" + findrequest.result.name); } }; findrequest.onerror = function(event){ console.log("failed"); }; //遍历查询模块,使用到了游标 objSto.openCursor().onsuccess = function(event){ var cursor = event.target.result; if (cursor){ console.log(cursor.key); console.log(cursor.value.name); cursor.continue(); } }; //更新数据模块 var updaterequest = objSto.put({ id:"6",name:"呜哈哈",value:"ccdsc" }); updaterequest.onsuccess = function(event){ console.log("更新成功"); }; //索引查询 var index = objSto.index("name"); var indexrequest = index.get("asdf"); indexrequest.onsuccess = function(event){ var result = event.target.result; if(result){ console.log(result); } }; /* 下面的代码可以把前面定义的personData里的数组插入库中 personData.forEach(function(person){ objSto.add(person); }) */ }; </script>
|