Html5数据存储值IndexedDB使用实践一

Html5有webDatabase和IndexedDB两种数据库,前者基于sqlite sql数据库,后者类似于mongodb的NoSql数据库。

从目前来看,nosql更加备受关注

上代码

<!DOCTYPE HTML>
<html xmlns=" http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>IndexedDB</title>
</head>
<body>
<script type="text/javascript">

    function addEvent(elm, evType, fn, useCapture) {
 
        if (elm.addEventListener) 
        {
            elm.addEventListener(evType, fn, useCapture);//DOM2.0
            return true;
        }
        else if (elm.attachEvent) {
            var r = elm.attachEvent('on' + evType, fn);//IE5+
            return !!r;
        }
        else {
            elm['on' + evType] = fn;//DOM 0
        }
    }
     //打开数据库(数据库不存在则会从新创建)
     /**
     * @param db_name 数据库名称
     * @param version 版本
     */
    function openOrCreateDB(db_name,version){
        var dbRequest =  window.indexedDB.open(db_name,version);
        return dbRequest;
    }
    //删除数据库
    function deleteIndexedDB(db_name)
    {
       return window.indexedDB.deleteDatabase(db_name);
    }
    //添加数据
    function addDataToStore(db)
    {
        var students=[{ 
            id:1001, 
            name:"Byron", 
            age:20 
        },{ 
            id:1002, 
            name:"Frank", 
            age:30 
        },{ 
            id:1003, 
            name:"Aaron", 
            age:22 
        }];
         //readwrite读写模式,read只读模式
        var transaction=db.transaction('students','readwrite'); 
        //开启事务操作

        addEvent(transaction,'complete',function(e){
             var store=transaction.objectStore('students'); 
             for(var i=0;i<students.length;i++){
                 store.add(students[i]);
            }

        },false)

      
       // deleteIndexedDB('testIndexedDB');
        
    }
    //添加监听器
    function addDBRequestListener(dbRequest,callback)
    {
          if(typeof(dbRequest.readyState)!='undefined' || dbRequest.readyState=='pending')
          {
            //request阻塞时调用
            addEvent(dbRequest,'blocked',function(e){
                e.status = {'msg':'blocked','code':-1};
                callback(e);
            },true);
            //request错误或者数据库创建失败
            addEvent(dbRequest,'error',function(e){
                  e.status = {'msg':'error','code':0};
                  callback(e);
            },true);
            //request成功或者数据库创建,操作成功
            addEvent(dbRequest,'success',function(e){
                e.status = {'msg':'success','code':1};
                callback(e);

            },true);
            //indexedDB版本更新(注意版本只能升,不能)或者数据库创建成功时
            //测试方式openOrCreateDB('testIndexedDB',1);和openOrCreateDB('testIndexedDB',2);
            addEvent(dbRequest,'upgradeneeded',function(e){
                   e.status = {'msg':'upgradeneeded','code':2};
                   callback(e);
            },true);
        }
    }

    var db = null;
    //返回 IDBOpenDBRequest
    var dbRequest = openOrCreateDB('testIndexedDB',1);  
    //添加监听事件
    addDBRequestListener(dbRequest,function(e)
    {
        console.log(e);
       if(e.status.code==1 && dbRequest.readyState=='done')
       {
            db = e.target.result;
            //监听数据库是否出错
            addEvent(db,'error',function(e){
                console.log(e);
                db.close();
            });

            addDataToStore(db); //添加数据
            
       }
       else if(e.status.code==2)  
       {
            var db=e.target.result;
            if(db.objectStoreNames.contains('students'))
            {
                db.deleteObjectStore('students');
            }
            if(!db.objectStoreNames.contains('students'))
            {
                //创建数据集,设置主键是id
                var store = db.createObjectStore('students',{autoIncrement: true,keyPath:"id"}); 
                //创建索引
                store.createIndex('nameIndex','name',{unique:true}); 
                store.createIndex('ageIndex','age',{unique:false}); 
            }
       }
       else if(e.status.code==-1)
       {
           
       }
    });

</script>
</body>
</html>

效果图:

Html5数据存储值IndexedDB使用实践一_第1张图片


Html5数据存储值IndexedDB使用实践一_第2张图片


错误:

由于设置了主键,再次添加相同的数据会触发该异常

你可能感兴趣的:(Html5数据存储值IndexedDB使用实践一)