HTML5本地存储indexDB新建数据库、数据库增删改查操作

HTML5本地存储indexDB新建数据库、数据库增删改查操作_第1张图片

代码如下:


<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />  
    <meta name="author" content="sina_mobile">
    <meta name="format-detection" content="telephone=no" />
    <title>indexDBtitle>
    <style>
        .outbox{
            width:300px;
            display:inline-block;
            border:1px solid #ccc;
        }
        .innerbox{
            height:400px;
            color:#333;
            line-height:20px;
            font-size:12px;
            width:300px;
        }
    style>
head>
<body>
<div class="outbox">
    <button>IndexDB新增操作button>
    <div class="innerbox" id="content1">div>
div>
<div class="outbox">
    <button>IndexDB修改操作button>
    <div class="innerbox" id="content2">div>
div>
<div class="outbox">
    <button>IndexDB删除操作button>
    <div class="innerbox" id="content3">div>
div>
<div class="outbox">
    <button>IndexDB遍历操作button>
    <div class="innerbox" id="content4">div>
div>
<script>
    var content = null;
    // 本演示使用的数据库名称
    var dbName = 'project';
    // 版本
    var version = 1;
    // 数据库数据结果
    var db;

    // 打开数据库
    var DBOpenRequest = window.indexedDB.open(dbName, version);

    // 如果数据库打开失败
    DBOpenRequest.onerror = function(event) {
        logError('数据库打开失败');
    };

    DBOpenRequest.onsuccess = function(event) {        
        // 存储数据结果
        db = DBOpenRequest.result;
    };

    // 下面事情执行于:数据库首次创建版本,或者window.indexedDB.open传递的新版本(版本数值要比现在的高)
    DBOpenRequest.onupgradeneeded = function(event) {
        db = event.target.result;

        db.onerror = function(event) {
            logError('数据库打开失败');
        };

        // 创建一个数据库存储对象
        var objectStore = db.createObjectStore(dbName, { 
            keyPath: 'id',
            autoIncrement: true
        });

        // 定义存储对象的数据项
        objectStore.createIndex('id', 'id', {
            unique: true    
        });
        objectStore.createIndex('name', 'name');
        objectStore.createIndex('begin', 'begin');
        objectStore.createIndex('end', 'end');
        objectStore.createIndex('person', 'person');
        objectStore.createIndex('remark', 'remark');
    };

    var method = {
        // 添加数据
        add: function (newItem) {
            var transaction = db.transaction([dbName], "readwrite");
            // 打开已经存储的数据对象
            var objectStore = transaction.objectStore(dbName);
            // 添加到数据对象中
            var objectStoreRequest = objectStore.add(newItem);        
            objectStoreRequest.onsuccess = function(event) {
                alert('新增成功!');
            };
        },
        // 更新数据
        update: function (id, data) {
            // 编辑数据
            var transaction = db.transaction([dbName], "readwrite");
            // 打开已经存储的数据对象
            var objectStore = transaction.objectStore(dbName);
            // 获取存储的对应键的存储对象
            var objectStoreRequest = objectStore.get(id);
            // 获取成功后替换当前数据
            objectStoreRequest.onsuccess = function(event) {
                // 当前数据
                var myRecord = objectStoreRequest.result;
                // 遍历替换
                for (var key in data) {
                    if (typeof myRecord[key] != 'undefined') {
                        myRecord[key] = data[key];
                    }
                }
                // 更新数据库存储数据                
                objectStore.put(myRecord);
            };
        },
        // 删除数据
        del: function (id) {
            // 打开已经存储的数据对象
            var objectStore = db.transaction([dbName], "readwrite").objectStore(dbName);            
            // 直接删除            
            var objectStoreRequest = objectStore.delete(id);
            // 删除成功后
        },
        // 通过主键key单个记录数据,主键是前面开始设置的相应key值
        get: function (key) {
            var transaction = db.transaction([dbName], "readwrite");
            var store = transaction.objectStore(dbName);
            var request = store.get(key); 
            request.onerror = function(){
                console.error('getDataByKey error');
            };
            request.onsuccess = function(e){
                var result = e.target.result;
                console.log('查找数据成功')
                console.log(result);
            };
        },
        // 遍历数据表
        cursor: function () {
            var transaction = db.transaction([dbName], "readwrite");
            var store = transaction.objectStore(dbName);
            var request = store.openCursor();//打开游标
            var arr = [];
            request.onsuccess = function(e) {
                var cursor = e.target.result;
                if (cursor) {
                    console.log(cursor);
                    arr.push(cursor.value);
                    cursor.continue();
                }
                content = JSON.stringify(arr);
            };
        }
    };
    let count = 0;
    // 新增
    document.querySelectorAll('button')[0].onclick = function () {
        // method.cursor();
        method.add({name: 'zyc' + count++, begin: '2012-12-22', end: '2122-32-44', person: 'dada', remark: 'dada'});
        method.cursor();    // 遍历所有数据库表project的记录,并输出到div里面
        document.querySelector("#content1").innerHTML = content;
    }
    // 修改
    document.querySelectorAll('button')[1].onclick = function () {
        method.update(3, {name: '我是更改的值id=3', begin: '2012-12-22', end: '2122-32-44', person: 'dada', remark: 'dada'});
        method.cursor();    // 遍历所有数据库表project的记录,并输出到div里面
        document.querySelector("#content2").innerHTML = content;
    }
    // 删除
    document.querySelectorAll('button')[2].onclick = function () {
        method.del(2); // 删除主键key id = 2的值
        method.cursor();    // 遍历所有数据库表project的记录,并输出到div里面
        document.querySelector("#content3").innerHTML = content;
    }
    // 遍历
    document.querySelectorAll('button')[3].onclick = function () {
        method.cursor();    // 遍历所有数据库表project的记录,并输出到div里面
        document.querySelector("#content4").innerHTML = content;
    }
    script>
body>
html>

你可能感兴趣的:(HTML5)