关于html5:indexedDB基本使用方法增删改查

48次阅读

共计 4032 个字符,预计需要花费 11 分钟才能阅读完成。

成果展现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>indexedDB</title>
</head>
<style>
    fieldset {
        margin-top: 50px;
        padding: 30px;
    }
</style>

<body>
    <h3>indexedDB web 数据库 增删改查 </h3>
    <div id="app">
        <fieldset>
            <button onclick="ctr('create')"> 增加 </button>
            <input id="addInput" type="text">
        </fieldset>
        <fieldset>
            <button onclick="ctr('retrieve')"> 查找 </button>
            <input id="findInput" type="text">
            <span id="viewFindResult"></span>
        </fieldset>
        <fieldset>
            <button onclick="ctr('update')"> 更新 </button>
            <input id="updateInput" type="text">
        </fieldset>
        <fieldset>
            <button onclick="ctr('delete')"> 删除 </button>
            <input id="delInput" type="text">
        </fieldset>
        <fieldset>
            <button onclick="ctr('clear')"> 清空 </button>
        </fieldset>
        <div>
            <!-- <ol>
                <li><button></button></li>
            </ol> -->
            <ul id="list"> 暂无数据 </ul>
        </div>
    </div>~~~~
    <script>
        let db, version = 1
        const addInputEle = document.getElementById("addInput");
        const updateInputEle = document.getElementById("updateInput");
        const delInputEle = document.getElementById("delInput");
        const findInputEle = document.getElementById("findInput");
        const viewFindResultEle = document.getElementById("viewFindResult");
        const listEle = document.getElementById("list");

        const request = indexedDB.open("user", version);
        // 监听数据库谬误
        request.onerror = function (e) {console.log("onerror", e);
        }

        // 监听数据库更新
        request.onupgradeneeded = function (e) {console.log("onupgradeneeded", e);
            db = e.target.result;
            var transaction = event.target.transaction
            if (!db.objectStoreNames.contains("users")) {
                const objectStore = db.createObjectStore("users", {keyPath: "username"});
                objectStore.createIndex('age', 'age', {unique: true});;
                objectStore.createIndex('fullName', 'fullName', {unique: false});;
            }
        }

        // 监听数据库连贯胜利
        request.onsuccess = function (e) {console.log("onsuccess", e);
            db = e.target.result;
            objectStore = db.transaction(['users'], 'readwrite')
                .objectStore('users');
            viewAll(objectStore)
        }
        // 操作数据库
        function ctr(method) {if (!db) {alert("数据库连贯中")
            }
            objectStore = db.transaction(['users'], 'readwrite')
                .objectStore('users');
            switch (method) {
                case "create":
                    createData(objectStore);
                    break;
                case "retrieve":
                    retrieveData(objectStore);
                    break;
                case "update":
                    updateData(objectStore);
                    break;
                case "delete":
                    deleteData(objectStore);
                    break;
                case "clear":
                    clearData(objectStore);
                    break;
            }
        }
        // 新增数据
        function createData(objectStore) {
            const username = addInputEle.value;
            if (!username) {alert("input 为空")
                return;
            }
            const req = objectStore
                .add({
                    username,
                    age: parseInt(Math.random() * 10000000) + "",
                    fullName: 1
                });
            req.onsuccess = function (e) {console.log('数据新增胜利', e);
                viewAll(objectStore);
            };

            req.onerror = function (e) {console.log('数据新增失败', e);
            }
        }
        // 检索数据
        function retrieveData(objectStore) {
            const username = findInputEle.value;
            if (!username) {alert("input 为空")
                return;
            }
            const req = objectStore.index("age")
                .get(username);
            req.onsuccess = function (e) {viewFindResultEle.innerText = e.target.result ? JSON.stringify(e.target.result) : "无此条记录";
                console.log('数据检索胜利', e);
            };

            req.onerror = function (e) {console.log('数据检索失败', e);
            }
        }
        // 更新数据
        function updateData(objectStore) {
            const username = updateInputEle.value;
            if (!username) {alert("input 为空")
                return;
            }
            const req = objectStore
                .put({
                    username,
                    age: 9999999999
                });
            req.onsuccess = function (e) {console.log('数据更新胜利', e);
                viewAll(objectStore)
            };

            req.onerror = function (e) {console.log('数据更新失败', e);
            }
        }
        // 删除数据
        function deleteData(objectStore) {
            const username = delInputEle.value;
            if (!username) {alert("input 为空")
                return;
            }
            const req = objectStore
                .delete(username);
            req.onsuccess = function (e) {console.log('数据删除胜利', e);
                viewAll(objectStore)
            };

            req.onerror = function (e) {console.log('数据删除失败', e);
            }
        }
        // 清空数据
        function clearData(objectStore) {
            const req = objectStore
                .clear();
            req.onsuccess = function (e) {console.log('数据清空胜利', e);
                viewAll(objectStore)
            };

            req.onerror = function (e) {console.log('数据清空失败', e);
            }
        }

        // 展现所有数据
        function viewAll(objectStore) {
            listEle.innerHTML = null;
            var flag = 0;
            objectStore.openCursor().onsuccess = function (e) {console.log("数据列表", e);
                const liEle = document.createElement("li");
                var cursor = e.target.result;
                if (cursor) {
                    flag++;
                    liEle.innerText = JSON.stringify(cursor.value);
                    listEle.appendChild(liEle);
                    cursor.continue();} else {if (flag == 0) {listEle.innerText = "暂无数据";} else {flag = 0;}
                }
            };
        }
    </script>
</body>

</html>

正文完
 0