关于indexedDB的基本使用

window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
    window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
    window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
    window.IDBCursor = window.IDBCursor || window.webkitIDBCursor || window.msIDBCursor;

    //连接数据库
    function connectDatabase() {
        var dbName = "indexedDBTest";
        var dbVersion = 20170633
        var idb;
        var dbConnect = indexedDB.open(dbName, dbVersion);
        //连接成功
        dbConnect.onsuccess = function(e) {
            idb = e.target.result;
            console.log(e);
            console.log("连接成功");
            //开启事物
            var tx = idb.transaction(["newUsers"], "readwrite");
            var store = tx.objectStore("newUsers");
            var value = {
                userId: 1,
                userName: "李四",
                address: "广东省"
            };

            var req = store.put(value);
            req.onsuccess = function(e) {
                console.log("保存成功");
            };
            req.onerror = function(e) {
                console.log("保存失败");
            }
        };
        dbConnect.onerror = function() {
            console.log("连接失败");
        };
        //数据库更新
        dbConnect.onupgradeneeded = function(e) {
            idb = e.target.result;
            var tx = e.target.transaction;
            var oldVersion = e.oldVersion;
            var newVersion = e.newVersion;
            console.log("数据库已经更新");
            //添加数据
            var name = "newUsers";
            var optionalParameters = {
                keyPath: "userId", //表示主键
                autoIncrement: true //主键是否自动增长
            };
            //createObjectStore(仓库名称,对象)
            var store = idb.createObjectStore(name, optionalParameters);
            //创建唯一索引
            var name = "userNameIndex";
            var keyPath = "userName";
            var optionalParameters = {
                unique: false,
                multiEntry: false
            };
            //创建唯一索引
            var idx = store.createIndex(name, keyPath, optionalParameters);
        };
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水痕01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值