indexedDB 增删改查

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="button" value="创建对象仓库和索引" onclick="connectDatabase();">
<input type="button" id="btnSaveData" value="保存数据" onclick="SaveData()">
<input type="button" id="btnSearchData" value="获取数据" onclick="getData()">
<input type="button" id="btnUpdateData" value="更新数据" onclick="updateData()">
<input type="button" id="btnDeleteData" value="删除数据" onclick="deleteData()">
<script>
    var db;
    var dbName = "HelloTestDatabase";
    var dbVersion = 1;
    function connectDatabase() {
        var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
        if(!indexedDB) {
            alert("你的浏览器不支持IndexedDB");
        } else {
            var request = indexedDB.open(dbName, dbVersion);
            request.onerror = function(event) {
              alert("Why didn't you allow my web app to use IndexedDB?!");
            };
            request.onsuccess = function(event) {
                console.log("onsuccess");
                db = event.target.result;
            };
            // dbVersion有变动时会触发这个事件
            // 数据的结构的变动需要在这里面操作
            request.onupgradeneeded = function(event) {
                console.log("onupgradeneeded");
                db = event.target.result;
                // 对象仓库创建部分
                // event.target.transaction属性值为一个IDBTransaction事务对象,此处代表版本更新事务
                let tx = event.target.transaction;  

                let name = 'IMMsg';
                // 主键设置
                let optionalParameters = {
                    keyPath: 'msgId',
                    autoIncrement: false
                };
                // 参数:对象仓库名, JavasScript对象(可选参数)   
                let store = db.createObjectStore(name, optionalParameters);  

                // 索引创建部分
                let IndexName = 'usernameIndex'; // 索引名
                let keyPath = 'username'; // 索引字段
                let IndexOptionalParameters = {
                    unique: false,
                    multiEntry: false
                };
                let idx = store.createIndex(IndexName, keyPath, IndexOptionalParameters); //参数:索引名
                console.log(idx);

                // 创建组合索引
                idx = store.createIndex('username-otherUsername', ['username','otherUsername']); // corrected
                console.log(idx);

                console.log('索引创建成功');
            };
        }
    }

    function SaveData() {
        //开启读写事务
        let tx = db.transaction(['IMMsg'],'readwrite');
        tx.oncomplete = function(){
            console.log('保存数据成功');
        }
        tx.onabort = function(){
            console.log('保存数据失败');
        }

        let store = tx.objectStore('IMMsg');
        let data1 = {
            msgId: 1,
            username: '张三',
            otherUsername: '李四',
            senderType: 1, // 1-发送发, 2-接收方
            msgType: 1 ,// 1-文本信息, 2-图片, 3-语音
            msgContent: '你好',
            isRead: 1 // 1-未读, 2-已读
        };
        store.put(data1);   // 使用 put 而不是 add 直接更新数据

        let data2 = {
            msgId: 2,
            username: '张三',
            otherUsername: '李四',
            senderType: 2, // 1-发送发, 2-接收方
            msgType: 1 ,// 1-文本信息, 2-图片, 3-语音
            msgContent: '我很好',
            isRead: 1 // 1-未读, 2-已读
        };
        store.put(data2);

        let data3 = {
            msgId: 3,
            username: '张三',
            otherUsername: '李四',
            senderType: 1, // 1-发送发, 2-接收方
            msgType: 1 ,// 1-文本信息, 2-图片, 3-语音
            msgContent: '最近在忙啥',
            isRead: 1 // 1-未读, 2-已读
        };
        store.put(data3);
        ///////////////////////////////////////////////////
        let data4 = {
            msgId: 4,
            username: '李四',
            otherUsername: '张三',
            senderType: 2, // 1-发送发, 2-接收方
            msgType: 1 ,// 1-文本信息, 2-图片, 3-语音
            msgContent: '你好',
            isRead: 1 // 1-未读, 2-已读
        };
        store.put(data4);

        let data5 = {
            msgId: 5,
            username: '李四',
            otherUsername: '张三',
            senderType: 1, // 1-发送发, 2-接收方
            msgType: 1 ,// 1-文本信息, 2-图片, 3-语音
            msgContent: '我很好',
            isRead: 1 // 1-未读, 2-已读
        };
        store.put(data5);

        let data6 = {
            msgId: 6,
            username: '张三',
            otherUsername: '王麻子',
            senderType: 1, // 1-发送发, 2-接收方
            msgType: 1 ,// 1-文本信息, 2-图片, 3-语音
            msgContent: 'xxxxxx',
            isRead: 1 // 1-未读, 2-已读
        };
        store.put(data6);
    }

    function deleteData() {
        var onlyKeyRange = IDBKeyRange.only(["张三","王麻子"]);
        var transaction = db.transaction(['IMMsg'], 'readwrite');
        var store = transaction.objectStore('IMMsg');
        var index = store.index('username-otherUsername');
        index.openCursor(onlyKeyRange).onsuccess = function(event) {
            var cursor = event.target.result;
            if (cursor) {
                store.delete(cursor.value.msgId);
                cursor.continue();
            } else {
                console.log("遍历完成");
            }
        };
    }

    function updateData() {
        var onlyKeyRange = IDBKeyRange.only(["张三","李四"]);
        var transaction = db.transaction(['IMMsg'], 'readwrite');
        var store = transaction.objectStore('IMMsg');
        var index = store.index('username-otherUsername');
        index.openCursor(onlyKeyRange).onsuccess = function(event) {
            var cursor = event.target.result;
            if (cursor) {
                cursor.value.isRead = 2;
                store.put(cursor.value);
                cursor.continue();
            } else {
                console.log("遍历完成");
            }
        };
    }

    function getData() {
        // 1. 游标遍历所有数据
        // var list = [];
        // var objectStore = db.transaction('IMMsg').objectStore('IMMsg');
        // objectStore.openCursor().onsuccess = function(event) {
        //     var cursor = event.target.result;
        //     if (cursor) {
        //         list.push(cursor.value);
        //         cursor.continue();
        //     } else {
        //         console.log('Get all data:');
        //         console.log(list);
        //     }
        // };

        //  
        // 2. 单个索引上使用游标
        // var onlyKeyRange = IDBKeyRange.only("李四");
        // var transaction = db.transaction(['IMMsg'], 'readonly');
        // var store = transaction.objectStore('IMMsg');
        // var index = store.index('usernameIndex');
        // var list = [];
        // index.openCursor(onlyKeyRange).onsuccess = function(event) {
        //     var cursor = event.target.result;
        //     if (cursor) {
        //     console.log('cursor.value:', cursor.value);
        //     list.push(cursor.value);
        //     cursor.continue();
        //     } else {
        //         console.log('list:', list);
        //     }
        // };
        // 游标更多用法
        // // 匹配所有在 "Bill" 前面的, 包括 "Bill"
        // var lowerBoundKeyRange = IDBKeyRange.lowerBound("Bill");
        // // 匹配所有在 “Bill” 前面的, 但是不需要包括 "Bill"
        // var lowerBoundOpenKeyRange = IDBKeyRange.lowerBound("Bill", true);
        // // 匹配所有在'Donna'后面的, 但是不包括"Donna"
        // var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true);
        // // 匹配所有在"Bill" 和 "Donna" 之间的, 但是不包括 "Donna"
        // var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true);

        // 3. 组合索引上使用游标
        var onlyKeyRange = IDBKeyRange.only(["张三","李四"]);
        var transaction = db.transaction(['IMMsg'], 'readonly');
        var store = transaction.objectStore('IMMsg');
        var index = store.index('username-otherUsername');
        var list = [];
        index.openCursor(onlyKeyRange).onsuccess = function(event) {
            var cursor = event.target.result;
            if (cursor) {
            console.log('cursor.value:', cursor.value);
            list.push(cursor.value);
            cursor.continue();
            } else {
                console.log('list:', list);
            }
        };
    }
</script>
</body>
</html>
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!