1. 程式人生 > >js操作indexedDB增刪改查示例

js操作indexedDB增刪改查示例

readwrite auto indexeddb object success win del 創建 fun

js操作indexedDB增刪改查示例

if (‘indexedDB‘ in window) {
    // 如果數據庫不存在則創建,如果存在但是version更大,會自動升級不會復制原來的版本
    var req = indexedDB.open("TestDB", 1);

    req.onupgradeneeded = function(e) {
        var db = req.result;
        // var store = db.createObjectStore("student", {autoIncrement: true}); 使用自增鍵
        // 創建student表
        var store = db.createObjectStore("student", {keyPath: ‘id‘});
        // 設置id為主鍵
        store.createIndex(‘student_id_unqiue‘,‘id‘, {unique: true});
    }

    req.onsuccess = function(event) {
        var students = [
            {id: 1, name: ‘小葉‘, age: ‘11‘},
            {id: 2, name: ‘小王‘, age: ‘12‘},
            {id: 3, name: ‘小張‘, age: ‘13‘}
        ];

        var db = event.target.result;
        // var transaction = db.transaction(‘student‘, ‘readwrite‘);
        var transaction = db.transaction([‘student‘], ‘readwrite‘);
        transaction.onsuccess = function(event) {
            console.log(‘[Transaction] 好了!‘);
        };

        var studentsStore = transaction.objectStore(‘student‘);
        students.forEach(function(student){
            var db_op_req = studentsStore.add(student);
            db_op_req.onsuccess = function() {
                console.log("存好了");
            }
        });

        studentsStore.count().onsuccess = function(event) {
            console.log(‘學生個數‘, event.target.result);
        };

        // 獲取id為1的學生
        studentsStore.get(1).onsuccess = function(event) {
            console.log(‘id為1的學生‘, event.target.result);
        };

        // 更新id為1的學生
        students[0].name = ‘小小葉‘;
        studentsStore.put(students[0]).onsuccess = function(event) {
            console.log(‘更新id為1的學生姓名‘, event.target.result);
        };

        // 刪除id為2的學生
        studentsStore.delete(2).onsuccess = function(event) {
            console.log(‘id為2的學生已經刪除‘);
        };
    }

    req.onerror = function() {
        console.log("數據庫出錯");
    }
}else{
    console.log(‘你的瀏覽器不支持IndexedDB‘);
}

js操作indexedDB增刪改查示例