IndexedDB(本地存储)

var students = [{
    id: 1001,
    name: "Byron",
    age: 24
}, {
    id: 1002,
    name: "Frank",
    age: 30
}, {
    id: 1003,
    name: "Aaron",
    age: 26
}, {
    id: 1004,
    name: "Casper",
    age: 26
}];

function hasIndexedDB() {
    if ("indexedDB" in window) {
        console.log("支持indexedDB!");
        return true;
    } else {
        console.log("不支持indexedDB!");
        return false;
    }
}

var dataBase = null;
// 打开数据库
function openIDB(IDBName, IDBVersion) {
    var IDBVersion = IDBVersion || 1;
    var IDBOpenDBRequest = indexedDB.open(IDBName, IDBVersion);

    IDBOpenDBRequest.onupgradeneeded = function(e) {
        var _db = e.target.result;
        createObjectStore(_db, "students");
        deleteObjectStore(_db, "firstOS");
        console.log('DB version changed to ' + IDBVersion);
    }
    IDBOpenDBRequest.onsuccess = function(e) {
        dataBase = e.target.result;
        // addData(dataBase,"students");
        // getDataByKey(dataBase,"students",1001);
        updateDataByKey(dataBase, "students", 1001);
        console.log("openIDB Success!");
    }
    IDBOpenDBRequest.onerror = function(e) {
        console.log("Error:" + e.currentTarget.error.message);
    }
}

// 添加数据
function addData(db, storeName) {
    var transaction = db.transaction(storeName, 'readwrite');
    var store = transaction.objectStore(storeName);

    for (var i = 0; i < students.length; i++) {
        store.add(students[i]);
    }
}

// 查询数据(根据关键字)
function getDataByKey(db, storeName, keyValue) {
    var transaction = db.transaction(storeName, 'readonly');
    var store = transaction.objectStore(storeName);

    var request = store.get(keyValue);
    request.onsuccess = function(e) {
        var student = e.target.result;
        console.log(student.name);
    };
}

// 更新数据
function updateDataByKey(db, storeName, keyValue) {
    var transaction = db.transaction(storeName, 'readwrite');
    var store = transaction.objectStore(storeName);
    var request = store.get(keyValue);
    request.onsuccess = function(e) {
        var student = e.target.result;
        student.age = 35;
        store.put(student);
    };
}

// 删除数据
function deleteDataByKey(db, storeName, keyValue) {
    var transaction = db.transaction(storeName, 'readwrite');
    var store = transaction.objectStore(storeName);
    store.delete(keyValue);
}

// 清空Store
function clearObjectStore(db, storeName) {
    var transaction = db.transaction(storeName, 'readwrite');
    var store = transaction.objectStore(storeName);
    store.clear();
}

// 删除Store(在onupgradeneeded里调用)
function deleteObjectStore(db, storeName) {
    if (db.objectStoreNames.contains(storeName)) {
        db.deleteObjectStore(storeName);
        console.log("deleteObjectStore:" + storeName + ",成功!");
    }
}

// 关闭dataBase
function closeIDB(db) {
    db.close();
}

// 删除dataBase
function deleteIDB(db) {
    indexedDB.deleteDatabase(db);
}

// 新增Store(在onupgradeneeded里调用)
function createObjectStore(db, storeName) {
    if (!db.objectStoreNames.contains(storeName)) {
        db.createObjectStore(storeName, {
            autoIncrement: true
        });
        console.log("createObjectStore:" + storeName + ",成功!");
    }
}

// 新增Store--带索引(在onupgradeneeded里调用)
function createObjectStoreWidthIndex(db, storeName) {
    if (!db.objectStoreNames.contains(storeName)) {
        var store = db.createObjectStore(storeName, {
            keyPath: "id"
        });
        // 创建两个索引表
        store.createIndex('nameIndex', 'name', {
            unique: true
        });
        store.createIndex('ageIndex', 'age', {
            unique: false
        });
        console.log("createObjectStore:" + storeName + ",成功!");
    }
}

// 获取数据(根据索引)
function getDataByIndex(db, storeName) {
    var transaction = db.transaction(storeName, 'readonly');
    var store = transaction.objectStore(storeName);
    var index = store.index("nameIndex");
    index.get('Byron').onsuccess = function(e) {
        var student = e.target.result;
        console.log(student.id);
    }
}

// 使用游标
function fetchStoreByCursor(db, storeName) {
    var transaction = db.transaction(storeName, 'readonly');
    var store = transaction.objectStore(storeName);
    var request = store.openCursor();
    request.onsuccess = function(e) {
        var cursor = e.target.result;
        if (cursor) {
            console.log(cursor.key);
            var currentStudent = cursor.value;
            console.log(currentStudent.name);
            cursor.continue();
        }
    };
}

// 索引与游标结合
function getDataByMultiple(db, storeName) {
    var transaction = db.transaction(storeName);
    var store = transaction.objectStore(storeName);
    var index = store.index("ageIndex");
    // index.openKeyCursor(26);
    var request = index.openCursor(IDBKeyRange.only(26));
    request.onsuccess = function(e) {
        var cursor = e.target.result;
        if (cursor) {
            var student = cursor.value;
            console.log(student.id);
            cursor.continue();
        }
    }
}

// 指定游标范围
// IDBKeyRange.only(value):只获取指定数据
// IDBKeyRange.lowerBound(value,isOpen):获取最小值是value的数据
// IDBKeyRange.upperBound(value,isOpen):获取最大值是value的数据
// IDBKeyRange.bound(value1,value2,isOpen1,isOpen2)

if (hasIndexedDB()) {
    openIDB("test1", 2);
}

 

参考:
  IndexedDB:浏览器端数据库
  HTML5本地存储——IndexedDB(一:基本使用)

 

posted @ 2016-11-16 15:44  huliang56  阅读(402)  评论(0编辑  收藏  举报