欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

IndexedDB 工具类 博客分类: HTMLJS JavaScriptHTML5 

程序员文章站 2024-03-14 23:52:53
...
var dbUtil = function () {

    var dbInfo={
        dbName:"Wei_You_DB",  // 名称
        dbVersion:"1.0"// 版本
    };
    var $this = this;
    var db;
    var indexedDB = window.indexedDB || window.webkitIndexedDB;

    if ('webkitIndexedDB' in window) {
        window.IDBTransaction = window.webkitIDBTransaction;
        window.IDBKeyRange = window.webkitIDBKeyRange;
    }

    function createDB_And_InitTables(objectStores,successCallBack,failedCallback){

        if(!objectStores || objectStores.length==0) return;

        var request = indexedDB.open(dbInfo.dbName);
        request.onsuccess = function(evt) {
            db = evt.target.result;
            // 只能在 setVersion 事务中创建 Object Stores;
            if (dbInfo.dbVersion!= db.version) {
                var setVReq = db.setVersion(dbInfo.dbVersion);
                // onsuccess 方法是唯一创建 Object Stores 的地方
                setVReq.onerror = dbError;
                setVReq.onsuccess = function() {
                    if(typeof objectStores == "string"){
                        if(!db.objectStoreNames.contains(objectStores)) {
//                            db.deleteObjectStore("ShoppingCart");
                            db.createObjectStore(objectStores,{keyPath: "id"});
                        }
                        return;
                    }
                    if(objectStores instanceof Array){
                        for(var i=0; i<objectStores.length ;i++){
                            if(!db.objectStoreNames.contains(objectStores[i])) {
//                            db.deleteObjectStore("ShoppingCart");
                                db.createObjectStore(objectStores[i],{keyPath: "id"});
                            }
                        }
                    }
                    successCallBack();
                };
            }
            else{
                successCallBack();
            }
        };
        request.onerror = failedCallback || function(e){
            console.error("exec createDB_And_InitTables error cause:"+ e.message);
        };
    }
    //插入或更新数据
    function insertOrUpdateData(data,objectStoreName,successCallBack,failedCallback){
        if(!data || !objectStoreName) return false;
        var trans = db.transaction([objectStoreName], IDBTransaction.READ_WRITE);
        var store = trans.objectStore(objectStoreName);
        var request = store.put(data);
        request.onsuccess = successCallBack;
        request.onerror = failedCallback;
    }
    function dbError(error){
        console.error(error);
    }

 

相关标签: JavaScript HTML5