HTML5教程 IndexdDB详解
沉沙 2018-09-07 来源 : 阅读 2061 评论 0

摘要:本篇教程探讨了HTML5教程 IndexdDB详解,希望阅读本篇文章以后大家有所收获,帮助大家HTML5+CSS3从入门到精通 。

本篇教程探讨了HTML5教程 IndexdDB详解,希望阅读本篇文章以后大家有所收获,帮助大家HTML5+CSS3从入门到精通 。

<

IndexdDB简介
html5中indexdDB是一种能在浏览器持久的存储结构化数据的数据库;且具有丰富的查询能力。
新建一个IndexdDB数据库
IDBOpenDBRequest定义有几个重要的属性:

onerror:新建或打开数据库失败的回调
onsuccess:新建或打开数据库成功的回调
onupgradeneeded:新建或打开数据库版本发生变化时触发的回调


以上的几个API均是异步执行,所以我们在它们的回调函数中处理我们需要的数据。
 

 1 function createIndexDB(dbName,version) {//根据数据库名称和数据库版本号来打开或者新建一个数据库
 2     var version = version || 1;
 3     var request = window.indexedDB.open(dbName,version);
 4     request.onerror = function(e) { //新建或打开数据失败的回调函数
 5         console.log(e);
 6     };
 7 
 8     request.onsuccess = function(e) { //新建或打开数据库成功的回调
 9         mydb.db = e.target.result; // 把result赋值给对象属性
10     };
11 
12     //初始化object store  也可以//删除object store
13     request.onupgradeneeded = function(e){
14         var db = e.target.result;
15         if(!db.objectStoreNames.contains(‘Employees‘)) { //是否包含员工这个对象
16             //db.createObjectStore(‘Employees‘,{keyPath:‘id‘}); // keyPath 指定对象的哪个属性作为主键
17             //db.createObjectStore(‘Employees‘,{autoIncrement:true}); //keyGenerate   主键自增长 ,任意值,
18             var store = db.createObjectStore(‘Employees‘,{keyPath:‘id‘}); // 同时返回一个store
19             store.createIndex(‘nameIndex‘,‘name‘,{unique:true}); //创建name的索引
20             store.createIndex(‘ageIndex‘,‘age‘,{unique:true});//创建age的索引
21         }
22         /*//删除object store
23         if(db.objectStoreNames.contains(‘Employees‘)) {  //先查询是否存在
24             db.deleteObjectStore(‘Employees‘);
25         }*/
26 
27         console.log("db version change to" + version);
28     };
29 
30 }

 新建数据库成功:

初始化一些数据:

 1 var mydb = {
 2     name:‘firstDB‘,
 3     version:1, //只能是整数,3.31--->会转成3
 4     db:null
 5 };
 6 // employee数据
 7 var Employee= [{
 8         id:‘lx001‘,
 9         name:‘lucas‘,
10         age:20
11     },
12     {
13         id:‘lx002‘,
14         name:‘lucy‘,
15         age:18
16     },
17     {
18         id:‘lx003‘,
19         name:‘mike‘,
20         age:22
21     },
22     {
23         id:‘lx004‘,
24         name:‘susan‘,
25         age:21
26     }
27 ];

添加数据Create:
 

1 //添加数据
2 function addData(db,storename){
3     var transaction = db.transaction(storename,"readwrite");//首先获取事务
4     var store = transaction.objectStore(storename);//根据事务获取对应的storename获取我们新建数据库的store
5     for(var i = 0; i < employee.length; i++) {//遍历我们的数据
6         store.add(employee[i]);//add到store中
7     }
8 }

 
调用addData函数添加数据:addData(mydb.db, ‘Employee‘)

成功添加数据;
indexdDB中事务
数据库都会有事务操作,indexdDB中根据数据库名字即read/write来获取事务,如添加数据库第一句代码。事务中要指定需要的object store;同时事务中具有3中模式:

read:只读,不可修改数据库可以并发执行;
readwrite:读写,可以修改数据库;
verionchange:数据库版本变更

indexdDB中的主键,索引,游标
主键:在新建数据库的时候指定数据的某个字段作为主键且该字段具有唯一性;如本文中就指定了id作为了主键(keyPath)。同时也可以使用自动增长数字作为键值(keyGenerator);同时也可以不指定。
索引:索引页是数据库中高效查询的一种方法;同时indexdDB也提供了创建索引的功能;如上新建数据库的时候我们就顺便创建了两个索引(nameIndex/ageIndex)。创建索引需要3个参数:索引名称,创建索引的字段,索引属性是否唯一;
游标:有了索引没有游标索引岂不是很寂寞,indexdDB同时也提供了创建游标的方法;我们可以使用游标来遍历object store了;
下面是创建游标:
 

 1 //使用游标来获取值,结合索引
 2 function getDataByFetch(db, storename,indexType, indexName) {
 3     var transaction = db.transaction(storename);
 4     var store = transaction.objectStore(storename);
 5     var index = store.index(indexType); //
 6     var request = index.openCursor(IDBKeyRange.only(indexName)); //打开游标,得到一个请求;store打开的是哪个类型的索引,only中就是哪个索引的值
 7     request.onsuccess = function(e) {
 8         var cursor = e.target.result;
 9         if(cursor) {
10             console.log(cursor.key)
11             var e = cursor.value;
12             console.log(e);
13             cursor.continue(); //游标下一位,没有会返回undefined
14         }
15     }
16 }

 


游标创建完成;
平常数据库中常常使用的CRUD,indexdDB也提供了相应的方法;上面已经介绍了添加数据
查询数据 Retrieve:


 1 //根据id获取数据
 2 function getDataByKey(db,storename,id){
 3     var transaction = db.transaction(storename,‘readwrite‘);//先获取事务
 4     var store = transaction.objectStore(storename);//获取object store
 5     var req = store.get(id); // 根据指定的keyPath的值查询 即id值
 6     req.onsuccess = function(e) {
 7         var employee = e.target.result;
 8         console.log(employee.name);
 9     }
10 }
11 //利用索引来获取值
12 function getDataByIndex(db,storename,indexType, indexName) {
13     var transaction = db.transaction(storename);//根据storename获取事务
14     var store = transaction.objectStore(storename); //storename为参数用事务获取store
15     var index = store.index(indexType);//使用index方法获取IDBIndex对象
16     index.get(indexName).onsuccess = function(e) {
17         var e = e.target.result;
18         console.log(e);
19     }
20 }
21 
22 //同时也可以使用游标来获取值,结合索引
23 function getDataByFetch(db, storename,indexType, indexName) {
24     var transaction = db.transaction(storename);
25     var store = transaction.objectStore(storename);
26     var index = store.index(indexType); //
27     var request = index.openCursor(IDBKeyRange.only(indexName)); //打开游标,得到一个请求;store打开的是哪个类型的索引,only中就是哪个索引的值
28     request.onsuccess = function(e) {
29         var cursor = e.target.result;
30         if(cursor) {
31             console.log(cursor.key)
32             var e = cursor.value;
33             console.log(e);
34             cursor.continue(); //游标下一位,没有会返回undefined
35         }
36     }
37 }


 
 
查询结果:
更新数据 update:

// 更新数据
function updateData(db, storename, id){
    var transaction = db.transaction(storename, ‘readwrite‘); //获取事务
    var store = transaction.objectStore(storename);// 得到指定的object store
    var req = store.get(id);//根据id查找指定的对象
    req.onsuccess = function(e) {
        var employee = e.target.result;//得到对象
        employee.age = 19;//修改值
        store.put(employee);//将修改之后的值放回指定的object store中
    };
}


删除数据 delete:

1 // 根据id删除指定数据
2 function deleteData(db, storename, id){
3     var transaction = db.transaction(storename, ‘readwrite‘);//获取事务
4     var store = transaction.objectStore(storename); // 得到对应的object store
5     store.delete(id);// 根据id删除对应store中的数据
6 }


清空object store

1 //清空object store
2 function clearStore(db, storename) {
3     var transaction = db.transaction(storename,‘readwrite‘); // 首先获取事务
4     var store = transaction.objectStore(storename); //其次得到指定的object store
5     store.clear(); // store调用clear方法
6 }

   

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标WEB前端HTML5/CSS3频道!

本文由 @沉沙 发布于职坐标。未经许可,禁止转载。
喜欢 | 4 不喜欢 | 0
看完这篇文章有何感觉?已经有4人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程