zoukankan      html  css  js  c++  java
  • js操作indexedDB增删改查示例

    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');
    }
    
  • 相关阅读:
    - (NSString *)description
    3.30 学习笔记
    常用的 博客
    iOS 比较好的博客
    iOS查看一段代码运行的时间
    tableview 第一次可以查看tableview 当退出第二次却会出现Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:]
    iphone 设置全局变量的几种方法
    java操作控件加密
    关闭windows 警报提示音
    HttpServletRequest简述
  • 原文地址:https://www.cnblogs.com/ye-hcj/p/10353187.html
Copyright © 2011-2022 走看看