zoukankan      html  css  js  c++  java
  • 谈谈html5存储之IndexdDB

    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 }
    View Code

     

    查询结果:

    更新数据 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 }

    怎么样, 是不是觉得indexdDB很强大呢?以上都是自己的一些个人学习收获,如有不对的地方欢迎大家批评指正。谢谢!

  • 相关阅读:
    接口新建学习---边界提取器
    Android Studio打包.so文件教程
    想要开发好的软件,必须学会这几项!
    你应该首先保护哪些应用程序?这个问题本身问错了!
    几周内搞定Java的10个方法
    翻译:程序员做些业余项目的重要性
    【源码】c#编写的安卓客户端与Windows服务器程序进行网络通信
    10款GitHub上最火爆的国产开源项目
    你的Android应用完全不需要那么多的权限
    2015年移动领域发展的九大趋势
  • 原文地址:https://www.cnblogs.com/leungUwah/p/5820156.html
Copyright © 2011-2022 走看看