讲师中心 微信公众号

工具推荐

视频效率加速
SoundView
SoundView

字幕擦除翻译、配音口型同步

updream

一键生成高质量推广成片

Seko
Seko

AI短剧一键生成成片

立刻MV
立刻MV

低成本歌曲 MV、视频生成

将数据库从服务器移到浏览器--indexedDB基本操作封装

胖雪小哥_3030

胖雪小哥_3030

发布时间:2017-06-23 14:04:45

|

2087人浏览过

|

来源于php中文网

原创

  数据库是属于服务器的,这是天经地义的事,但是有时候数据也许并非需要存储在服务器,但是这些数据也是一条一条的记录,怎么办?今天来带领你领略一下h5的一个新特性--indexeddb的风骚。你会情不自禁的发出感叹--不可思议!

一、链接数据库

  indexedDB没有创建数据库的概念,你可以直接链接数据库,如果你链接的数据库并不存在,那么会自动的创建一个数据库。看下面的这个例子。

  

浏览器会话(免费版)
浏览器会话(免费版)

浏览器会话管理免费版,支持一次性页面抓取、基础会话列表与简易调试。

下载
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><button type="" id='conbtn'>链接数据库</button><script>// In the following line, you should include the prefixes of implementations you want to test.    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;   // DON'T use "var indexedDB = ..." if you're not in a function.
   // Moreover, you may need references to some window.IDB* objects:   window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
   window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange   // (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
   function connectDB(name,version,success,error){
         let dbConnect = indexedDB.open(name,version);
              dbConnect.onsuccess = function(e){
                  console.log('数据库链接成功!');
                success(e.target.result);            
            }
            dbConnect.onerror = function(e){
                console.log('数据库链接失败!');
                error(e);
            }
            dbConnect.onupgradeneeded = function(e){
                success(e.target.result);
                let oldVersion = e.oldVersion;
                let newVersion = e.newVersion;
                console.log('数据库更新成功,旧的版本号为:'+oldVersion+",新的版本号为:"+newVersion);
            }
   }
   window.onload=function(){
           let btn  = document.getElementById('conbtn');
           btn.onclick = function(){
               connectDB('haha',1,function(){
                   console.log('链接成功,或者更新成功回调函数');
               },function(){
                   console.log('链接失败回调函数!')
               });
           }
   }</script></body></html>

  我点了两次链接数据库,结果是这样的。

 

  在Application的indexedDB中我们发现多了一个东西。

  

  可以看到haha数据库已经成功建立了。

  indexedDB的open方法用来链接或者更新数据库,第一次创建也认为是一次更新。第一个参数是数据库的名字,第二个参数为版本号。第一次创建或者版本号发生改变时出发更新事件upgradeneeded,链接成功后出发success事件,链接出错时触发error事件。

二、建表和索引

  

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><button type="" id='conbtn'>链接数据库</button><script>// In the following line, you should include the prefixes of implementations you want to test.    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;   // DON'T use "var indexedDB = ..." if you're not in a function.
   // Moreover, you may need references to some window.IDB* objects:   window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
   window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange   // (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
   function connectDB(name,version,success,update,error){
         let dbConnect = indexedDB.open(name,version);
              dbConnect.onsuccess = function(e){
                  console.log('数据库链接成功!');
                success(e.target.result);            
            }
            dbConnect.onerror = function(e){
                console.log('数据库链接失败!');
                error(e);
            }
            dbConnect.onupgradeneeded = function(e){
                update(e.target.result);
                let oldVersion = e.oldVersion;
                let newVersion = e.newVersion;
                console.log('数据库更新成功,旧的版本号为:'+oldVersion+",新的版本号为:"+newVersion);
            }
   }       function createTable(idb,storeName,key,idxs){if(!idb){
            console.log(idb);return ;
        }if(!key || !idxs){
            console.log('参数错误');return ;
        }if(!storeName){
            console.log('storeName必须');return ;
        }try{var store = idb.createObjectStore(storeName,key);
            console.log('数据库存储对象(table)创建成功');for(var i = 0;i<idxs.length;i++){var idx = idxs[i];
                store.createIndex(idx.indexName,idx.keyPath,idx.optionalParameters);
                    console.log('索引'+idx.indexName+'创建成功');
            }
        }catch(e){
            console.log('建表出现错误');
            console.log(JSON.stringify(e))
        }
    }
   window.onload=function(){
           let btn  = document.getElementById('conbtn');
           btn.onclick = function(){
               connectDB('haha',1,                 function(idb){
                   console.log('链接成功,或者更新成功回调函数');
               },function(idb){                   createTable(idb,'test',{keyPath:'id',autoIncrement:true},[
                       {
                       indexName:'testIndex',
                     keyPath:'name',
                     optionalParameters:{
                         unique:true,
                         multiEntry:false }}]);                   
               },function(){
                   console.log('链接失败回调函数!')
               });
           }
   }</script></body></html>

 

  我点了一下按钮结果时这样的。

  

  

  这里用到的两个核心方法时createObjectStore,和createIndex,这两个方法必须在数据库发生更新的事件中执行。

  createObjectStore方法可以理解成是创建表,接受第一个参数为一个字符串,表示表名,第二个参数是一个对象,指定主键相关的东西,{keyPath:'主键是哪个字段',autoIncrement:是否自增}。

  createIndex方法是创建索引的,接受三个参数,第一个是一个字符串,表示索引的名字,第二个参数表示字段名(谁的索引),第三个参数是个对象,具体自己查去。索引的作用是在查询操作时可以用到,不详讲,自行google吧。

三、添加数据

  

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><button type="" id='conbtn'>链接数据库</button><button type="" id='add'>添加数据</button><script>// In the following line, you should include the prefixes of implementations you want to test.    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;   // DON'T use "var indexedDB = ..." if you're not in a function.
   // Moreover, you may need references to some window.IDB* objects:   window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
   window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange   // (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
   function connectDB(name,version,success,update,error){
         let dbConnect = indexedDB.open(name,version);
              dbConnect.onsuccess = function(e){
                  console.log('数据库链接成功!');
                success(e.target.result);            
            }
            dbConnect.onerror = function(e){
                console.log('数据库链接失败!');
                error(e);
            }
            dbConnect.onupgradeneeded = function(e){
                update(e.target.result);
                let oldVersion = e.oldVersion;
                let newVersion = e.newVersion;
                console.log('数据库更新成功,旧的版本号为:'+oldVersion+",新的版本号为:"+newVersion);
            }
   }       function createTable(idb,storeName,key,idxs){if(!idb){
            console.log(idb);return ;
        }if(!key || !idxs){
            console.log('参数错误');return ;
        }if(!storeName){
            console.log('storeName必须');return ;
        }try{var store = idb.createObjectStore(storeName,key);
            console.log('数据库存储对象(table)创建成功');for(var i = 0;i<idxs.length;i++){var idx = idxs[i];
                store.createIndex(idx.indexName,idx.keyPath,idx.optionalParameters);
                    console.log('索引'+idx.indexName+'创建成功');
            }
        }catch(e){
            console.log('建表出现错误');
            console.log(JSON.stringify(e))
        }
    }function add(storeName,values){
    connectDB('haha',1,function(idb){var ts = idb.transaction(storeName,"readwrite");var store = ts.objectStore(storeName);        for(var i = 0;i<values.length;i++){
            (function(i){var value = values[i];var req = store.put(value);
                req.onsuccess = function(){
                    console.log("添加第"+i+"个数据成功");
                }
                req.onerror = function(e){
                    console.log("添加第"+i+"个数据失败");
                    console.log(JSON.stringify(e));
                }                            
            })(i)

        }
        ts.oncomplete = function(){
            console.log('添加数据事务结束!');
        }
    },function(){},function(){});

                
    }
   window.onload=function(){
           let btn  = document.getElementById('conbtn');
           btn.onclick = function(){
               connectDB('haha',1,                 function(idb){
                   console.log('链接成功,或者更新成功回调函数');
               },function(idb){
                   createTable(idb,'test',{keyPath:'id',autoIncrement:true},[
                       {
                       indexName:'testIndex',
                     keyPath:'name',
                     optionalParameters:{
                         unique:true,
                         multiEntry:false }}]);                   
               },function(){
                   console.log('链接失败回调函数!')
               });
           }
           let add1 = document.getElementById('add');
           add1.onclick = function(){
               add('test',[{name:"fjidfji",a:'uuuu'}])
           }
   }</script></body></html>

 

 

  比较神奇的是你在建表的时候不需要指定你的字段,再添加数据时可以随便加。添加数据用到的是表对象的put方法,之前需要一个事务,从事务调个方法拿到存储对象(可以理解为表),具体看看例子就明白了。

四、查询数据

Document链接数据库添加数据查询

 

   查询操作主要用到了游标,这个说起来还比较多,没时间说了,自行google。还有很多的操作这里不讲了。给一个我封装的不是很好的简易库,仅供参考。

   一个简易库。

(function(window){'use strict';
    window.dbUtil={
    indexedDB :(window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB),

    IDBTransaction :(window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction),

    IDBKeyRange :(window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange),

    IDBCursor : (window.IDBCursor || window.webkitIDBCursor || window.msIDBCursor),            
    idb:null,
    dbName:"",
    dbVersion:"",/**
     * 初始化数据库,创建表和建立链接
     * @param  {[type]} dbName    [description]
     * @param  {[type]} dbVersion [description]
     * @param  {[type]} storeObjs [description]
     * @return {[type]}           [description]     */initDB:function (dbName,dbVersion,storeObjs){this.dbName = dbName;this.dbVersion = dbVersion;var dbConnect = this.indexedDB.open(this.dbName,this.dbVersion);var self = this;
        dbConnect.onsuccess = function(e){
            self.idb = e.target.result;
            self.log('数据库链接成功!');                
        }
        dbConnect.onerror = function(e){
            console.log(e)
            self.log('数据库链接失败!');
        }
        dbConnect.onupgradeneeded = function(e){
            self.idb = e.target.result;var ts = e.target.transaction;var oldVersion = e.oldVersion;var newVersion = e.newVersion;
            self.log('数据库更新成功,旧的版本号为:'+oldVersion+",新的版本号为:"+newVersion);if(storeObjs){for(var k = 0,len=storeObjs.length;k<len;k++){var storeObj = storeObjs[k];var storeName = storeObj.storeName;var key = storeObj.key;var idxs = storeObj.idxs;

                    self.createTable(storeName,key,idxs)
                }
            }
        }
    },/**
     * 创建数据库存储对象(表)
     * @param  {[type]} key [description]
     * @param  {[type]}     [description]
     * @return {[type]}     [description]     */createTable:function(storeName,key,idxs){var self = this;var idb = self.idb;if(!idb){
            self.log('数据库没有链接');return ;
        }if(!key || !idxs){
            self.log('参数错误');return ;
        }if(!storeName){
            self.log('storeName必须');return ;
        }try{var store = idb.createObjectStore(storeName,key);
            self.log('数据库存储对象(table)创建成功');for(var i = 0;i<idxs.length;i++){var idx = idxs[i];
                store.createIndex(idx.indexName,idx.keyPath,idx.optionalParameters);
            self.log('索引'+idx.indexName+'创建成功');
            }
        }catch(e){
            self.log('建表出现错误');
            console.log(JSON.stringify(e))
        }
    },/**
     * [add description]
     * @param {[type]} storeName [description]
     * @param {[type]} values    [description]     */add:function(storeName,values){var dbConnect = this.indexedDB.open(this.dbName,this.dbVersion);var self = this;
        dbConnect.onsuccess = function(e){var idb = e.target.result;var ts = idb.transaction(storeName,"readwrite");var store = ts.objectStore(storeName);for(var i = 0;i<values.length;i++){
                (function(i){var value = values[i];var req = store.put(value);
                    req.onsuccess = function(){
                        self.log("添加第"+i+"个数据成功");
                    }
                    req.onerror = function(e){
                        self.log("添加第"+i+"个数据失败");
                        self.log(JSON.stringify(e));
                    }                            
                })(i)

            }
            ts.oncomplete = function(){
                self.log('添加数据事务结束!');
            }
                    
        }

    },/**
     * [select description]
     * @param  {[type]}   storeName [description]
     * @param  {[type]}   count     [description]
     * @param  {Function} callback  [description]
     * @param  {[type]}   indexName [description]
     * @return {[type]}             [description]     */select:function(storeName,count,callback,indexName){var dbConnect = this.indexedDB.open(this.dbName,this.dbVersion);var self = this;var total = 0;var data = [];
        dbConnect.onsuccess = function(e){
            self.log("数据库链接成功!");var idb = e.target.result;var ts = idb.transaction(storeName,"readonly");var store = ts.objectStore(storeName);var req = store.count();var req2 = null;
            req.onsuccess = function(){
                total = this.result;var realCount = (count<=total)?count:total;if(typeof indexName == 'undefined'){var range = IDBKeyRange.bound(0,"9999999999999999999999");
                    req2 = store.openCursor(range,'prev');var cc = 0;
                    req2.onsuccess = function(){var cursor = this.result;if(total == 0){
                            callback([]);return;
                        }if(cursor){                        
                            cc++;
                            data.push(cursor.value);if(cc==realCount){
                                callback(data);return;
                            }
                            cursor.continue();
                        }
                    }
                    req2.onerror = function(){
                        self.log("检索出错")
                    }
                }else{//待写                }                        
            }

        }
    },/**
     * [delete description]
     * @param  {[type]} storeName [description]
     * @param  {[type]} key       [description]
     * @return {[type]}           [description]     */delete:function(storeName,key,callback){var dbConnect = this.indexedDB.open(this.dbName,this.dbVersion);
        let self = this;
        dbConnect.onsuccess = function(e){var idb = e.target.result;var ts = idb.transaction(storeName,'readwrite');var store = ts.objectStore(storeName);
            store.delete(key);
            self.log('删除成功!');if(callback){
                callback();
            }
        }
    },/**
     * [funciton description]
     * @param  {[type]} storeName    [description]
     * @param  {[type]} key          [description]
     * @param  {[type]} existCall    [description]
     * @param  {[type]} notExistCall [description]
     * @return {[type]}              [description]     */isExist:function(storeName,key,existCall,notExistCall){var dbConnect = this.indexedDB.open(this.dbName,this.dbVersion);
        dbConnect.onsuccess = function(e){var idb = e.target.result;var ts = idb.transaction(storeName,'readonly');var store = ts.objectStore(storeName);var req = store.get(key);
            req.onsuccess = function(){if(this.result == undefined){
                    notExistCall();
                }else{
                    existCall(this.result);
                }
            }
            req.onerror = function(){
                notExistCall();
            }
        }
    },/**
     * clear
     * @param  {[type]} storeName [description]
     * @return {[type]}           [description]     */clear:function clearObjectStore(storeName){var dbConnect = this.indexedDB.open(this.dbName,this.dbVersion);
            dbConnect.onsuccess = function(e){var idb = e.target.result;var ts = idb.transaction(storeName,'readwrite');var store = ts.objectStore(storeName);
                store.clear();
            }        
    },/**
     * 删除数据库
     * @param  {[type]} dbName [description]
     * @return {[type]}        [description]     */dropDatabase:function(dbName){this.indexedDB.deleteDatabase(dbName);this.log('成功删除数据库:'+dbName);
    },/**
     * [log description]
     * @param  {[type]} msg [description]
     * @return {[type]}     [description]     */log:function(msg){
        console.log((new Date()).toTimeString()+":"+msg)
    }

    }

})(window);

 

五、使用indexedDB的优缺点

  1、优点:可以将一些数据放到浏览器端,不用和服务器交互就可以实现一些功能,减轻服务器负担,加快响应速度。

  2、缺点:

  (1)不可靠:用户可能删处indexedDB,而且更换浏览器或者设备后这些数据就没了。

  2)不便于数据采集:有很多时候将数据存到服务器是为了获得一些数据,如果放到浏览器端,这些数据比较难获取。

 (3)无法共享:不同用户没办法共享数据,甚至时一个设备的不同浏览器也没法共享。

  所以,是否适用indexedDB要进行一下利弊权衡,不是有了indexedDB就啥也不管,一骨脑将数据放进去。 

  

  最近两个课程设计,还有面试, 文章写的比较匆忙,如有问题请各位园友批评指正。最近找实习,各位园友要是我写的东西还可以而且公司招聘实习生的话可以给大熊一个机会,谢谢!

热门AI工具

更多
音述AI
音述AI Hot

一款AI音频处理工具,主要用于音述AI是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区,适合需要提升相关任务效率的用户。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

SkildArt
SkildArt Hot

SkildArt是一款AI文本写作工具,一站式 AI 视觉创作平台。

VibeKnow
VibeKnow Hot

一款AI视频创作工具,主要用于全球首个AI知识视频创作平台,文档、文章、网页,一键生成视频,适合需要提升相关任务效率的用户。

蛙蛙写作

一款AI论文写作工具,主要用于超级AI智能写作助手,适合需要提升相关任务效率的用户。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

花生AI
花生AI Hot

一款AI视频创作工具,主要用于B站推出的AI视频创作工具,适合需要提升相关任务效率的用户。

火山引擎

火山引擎是一款面向企业的云计算与AI服务平台。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

相关专题

更多
Navicat创建数据库教程
Navicat创建数据库教程

本专题整理Navicat创建数据库相关教程,介绍新建前的准备、基础设置和创建后的检查方法。内容兼顾入门学习及实际使用需求,帮助用户了解不同数据库类型下的操作差异,为后续建表、保存数据和日常管理提供参考。

20

2026.11.20

Navicat入门教程大全
Navicat入门教程大全

本专题整理Navicat入门教程,从认识软件界面到开展数据库操作,介绍初次使用需要了解的知识和方法。内容兼顾连接配置、数据管理及日常使用中的疑问,方便用户按学习进度查阅,为后续实践和独立操作打好基础。

20

2026.11.20

Navicat数据库连接配置指南
Navicat数据库连接配置指南

从确认数据库信息到建立可用连接,本专题串联Navicat连接数据库的相关知识和操作方法。既有初次配置时需要了解的基础内容,也有连接后的检查思路,方便用户按实际需求查阅教程,逐步熟悉数据库连接的设置流程。

0

2026.11.20

PHP8.6数组与数据处理教程
PHP8.6数组与数据处理教程

本专题汇总PHP8.6数组与数据处理教程,涵盖CSV读取和导出、引用遍历删除、array_filter回调模式、配置键名冲突、pathinfo文件名校验、GMP大整数进制转换及UTF-8正则筛选,说明升级兼容变化、输入范围和失败处理方法。

60

2026.11.20

PHP8.6升级迁移教程
PHP8.6升级迁移教程

本专题汇总PHP8.6升级迁移与弃用接口改造教程,涵盖反射调用、对象属性赋值、标识符更名、构造函数与__debugInfo调整,以及插件类名检查、常量导出、ArrayIterator排序、SPL和DTO查询参数转换,帮助梳理弃用提示并完成代码兼容改造。

0

2026.11.20

PHP8.6安装配置与FPM运维教程
PHP8.6安装配置与FPM运维教程

本专题汇总PHP8.6正式版安装部署与FPM运维教程,涵盖Linux并存安装、独立ini配置、扩展重新编译、Nginx切换与回滚、FPM状态监控和慢日志排查,以及环境变量、请求超时、OPcache刷新和预加载配置。

40

2026.11.20

Nginx CVE-2026-123007排查与防护指南
Nginx CVE-2026-123007排查与防护指南

Nginx HTTP/2漏洞该怎么修复?本专题围绕CVE-2026-123007,介绍安全版本升级、模块兼容检查和配置恢复方法,以及日志排查、权限设置等后续加固操作,方便你按实际部署情况查找对应教程。

40

2026.11.20

GoFrame框架Web开发与路由中间件
GoFrame框架Web开发与路由中间件

本专题聚焦GoFrame框架的Web开发,拆解路由注册与匹配规则、请求参数获取、参数校验与中间件执行顺序,说明统一响应、JWT鉴权、文件上传与接口文档生成的落地方式,并补充优雅重启与测试实践。

80

2026.11.17

GoFrame框架安装与gf命令行工具
GoFrame框架安装与gf命令行工具

本专题围绕GoFrame框架的安装与工具链配置展开,讲清Go版本要求、gf命令行的安装方式、代理镜像与依赖准备,说明项目初始化、热编译、交叉编译打包的做法,并整理安装阶段的常见报错与验证步骤。

100

2026.11.17

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Firebug入门教程
Firebug入门教程

共7课时 | 5.3万人学习

前端最全HTTP基础原理及应用
前端最全HTTP基础原理及应用

共12课时 | 2.2万人学习

后盾网HTML5视频教程
后盾网HTML5视频教程

共38课时 | 9.7万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn