搜尋
首頁web前端H5教程將資料庫從伺服器移到瀏覽器--indexedDB基本操作封裝

將資料庫從伺服器移到瀏覽器--indexedDB基本操作封裝

Jun 23, 2017 pm 02:04 PM
firefoxiewebkit資料庫伺服器瀏覽器

  資料庫是屬於伺服器的,這是天經地義的事,但是有時候資料也許並非需要儲存在伺服器,但是這些資料也是一條一條的記錄,怎麼辦?今天來帶領你來領略H5的一個新特性--indexedDB的風騷。你會情不自禁的發出感嘆--不可思議!

一、連結資料庫

  indexedDB沒有建立資料庫的概念,你可以直接連結資料庫,如果你連結的資料庫不存在,那麼會自動的建立一個資料庫。看下面的這個例子。

  

nbsp;html><meta><title>Document</title><button>链接数据库</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&#39;T use "var indexedDB = ..." if you&#39;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&#39;t need window.mozIDB*)
   function connectDB(name,version,success,error){
         let dbConnect = indexedDB.open(name,version);
              dbConnect.onsuccess = function(e){
                  console.log(&#39;数据库链接成功!&#39;);
                success(e.target.result);            
            }
            dbConnect.onerror = function(e){
                console.log(&#39;数据库链接失败!&#39;);
                error(e);
            }
            dbConnect.onupgradeneeded = function(e){
                success(e.target.result);
                let oldVersion = e.oldVersion;
                let newVersion = e.newVersion;
                console.log(&#39;数据库更新成功,旧的版本号为:&#39;+oldVersion+",新的版本号为:"+newVersion);
            }
   }
   window.onload=function(){
           let btn  = document.getElementById(&#39;conbtn&#39;);
           btn.onclick = function(){
               connectDB(&#39;haha&#39;,1,function(){
                   console.log(&#39;链接成功,或者更新成功回调函数&#39;);
               },function(){
                   console.log(&#39;链接失败回调函数!&#39;)
               });
           }
   }</script>

  我點了兩次連結資料庫,結果是這樣的。

 

  在Application的indexedDB中我們發現多了一個東西。

  

  可以看到haha資料庫已經成功建立了。

  indexedDB的open方法用來連結或更新資料庫,第一次建立也認為是一次更新。第一個參數是資料庫的名字,第二個參數為版本號。第一次建立或版本號改變時出發更新事件upgradeneeded,連結成功後出發success事件,連結出錯時觸發error事件。

二、建表和索引

  

nbsp;html><meta><title>Document</title><button>链接数据库</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&#39;T use "var indexedDB = ..." if you&#39;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&#39;t need window.mozIDB*)
   function connectDB(name,version,success,update,error){
         let dbConnect = indexedDB.open(name,version);
              dbConnect.onsuccess = function(e){
                  console.log(&#39;数据库链接成功!&#39;);
                success(e.target.result);            
            }
            dbConnect.onerror = function(e){
                console.log(&#39;数据库链接失败!&#39;);
                error(e);
            }
            dbConnect.onupgradeneeded = function(e){
                update(e.target.result);
                let oldVersion = e.oldVersion;
                let newVersion = e.newVersion;
                console.log(&#39;数据库更新成功,旧的版本号为:&#39;+oldVersion+",新的版本号为:"+newVersion);
            }
   }       function createTable(idb,storeName,key,idxs){if(!idb){
            console.log(idb);return ;
        }if(!key || !idxs){
            console.log(&#39;参数错误&#39;);return ;
        }if(!storeName){
            console.log(&#39;storeName必须&#39;);return ;
        }try{var store = idb.createObjectStore(storeName,key);
            console.log(&#39;数据库存储对象(table)创建成功&#39;);for(var i = 0;i<idxs.length;i++){var idx = idxs[i];
                store.createIndex(idx.indexName,idx.keyPath,idx.optionalParameters);
                    console.log(&#39;索引&#39;+idx.indexName+&#39;创建成功&#39;);
            }
        }catch(e){
            console.log(&#39;建表出现错误&#39;);
            console.log(JSON.stringify(e))
        }
    }
   window.onload=function(){
           let btn  = document.getElementById(&#39;conbtn&#39;);
           btn.onclick = function(){
               connectDB(&#39;haha&#39;,1,                 function(idb){
                   console.log(&#39;链接成功,或者更新成功回调函数&#39;);
               },function(idb){                   createTable(idb,&#39;test&#39;,{keyPath:&#39;id&#39;,autoIncrement:true},[
                       {
                       indexName:&#39;testIndex&#39;,
                     keyPath:&#39;name&#39;,
                     optionalParameters:{
                         unique:true,
                         multiEntry:false }}]);                   
               },function(){
                   console.log(&#39;链接失败回调函数!&#39;)
               });
           }
   }</script>

 

  我點了一下按鈕結果時這樣的。

  

  

  這裡用到的兩個核心方法時createObjectStore,和createIndex,這兩個方法必須在資料庫發生更新的事件中執行。

  createObjectStore方法可以理解成是創建表,接受第一個參數為一個字串,表示表名,第二個參數是一個對象,指定主鍵相關的東西,{keyPath:'主鍵是哪個字段',autoIncrement:是否自增}。

  createIndex方法是建立索引的,接受三個參數,第一個是字串,表示索引的名字,第二個參數表示欄位名稱(誰的索引),第三個參數是個對象,具體自己查去。索引的作用是在查詢操作時可以用到,不詳講,自行google吧。

三、新增資料

  

nbsp;html><meta><title>Document</title><button>链接数据库</button><button>添加数据</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&#39;T use "var indexedDB = ..." if you&#39;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&#39;t need window.mozIDB*)
   function connectDB(name,version,success,update,error){
         let dbConnect = indexedDB.open(name,version);
              dbConnect.onsuccess = function(e){
                  console.log(&#39;数据库链接成功!&#39;);
                success(e.target.result);            
            }
            dbConnect.onerror = function(e){
                console.log(&#39;数据库链接失败!&#39;);
                error(e);
            }
            dbConnect.onupgradeneeded = function(e){
                update(e.target.result);
                let oldVersion = e.oldVersion;
                let newVersion = e.newVersion;
                console.log(&#39;数据库更新成功,旧的版本号为:&#39;+oldVersion+",新的版本号为:"+newVersion);
            }
   }       function createTable(idb,storeName,key,idxs){if(!idb){
            console.log(idb);return ;
        }if(!key || !idxs){
            console.log(&#39;参数错误&#39;);return ;
        }if(!storeName){
            console.log(&#39;storeName必须&#39;);return ;
        }try{var store = idb.createObjectStore(storeName,key);
            console.log(&#39;数据库存储对象(table)创建成功&#39;);for(var i = 0;i<idxs.length;i++){var idx = idxs[i];
                store.createIndex(idx.indexName,idx.keyPath,idx.optionalParameters);
                    console.log(&#39;索引&#39;+idx.indexName+&#39;创建成功&#39;);
            }
        }catch(e){
            console.log(&#39;建表出现错误&#39;);
            console.log(JSON.stringify(e))
        }
    }function add(storeName,values){
    connectDB(&#39;haha&#39;,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(&#39;添加数据事务结束!&#39;);
        }
    },function(){},function(){});

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

 

 

  比較神奇的是你在建表的時候不需要指定你的字段,再添加數據時可以隨便加。增加資料用到的是表物件的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>###### ######五、使用indexedDB的優缺點######  1、優點:可以將一些資料放到瀏覽器端,不用和伺服器互動就可以實現一些功能,減輕伺服器負擔,加快回應速度。 ######  2、缺點:######  (1)不可靠:使用者可能刪處indexedDB,而且更換瀏覽器或裝置後這些資料就沒了。 ######  2)不方便於資料收集:有很多時候將資料存到伺服器是為了取得一些數據,如果放到瀏覽器端,這些資料比較難取得。 ###### (3)無法分享:不同使用者沒辦法分享數據,甚至時一個裝置的不同瀏覽器也沒辦法共用。 ######  所以,是否適用indexedDB要進行一下利弊權衡,不是有了indexedDB就啥也不管,一骨腦將資料放進去。 ######  ######  最近兩個課程設計,還有面試, 文章寫的比較匆忙,如有問題請各位園友批評指正。最近找實習,各位園友要是我寫的東西還可以而且公司招募實習生的話可以給大熊一個機會,謝謝! ###</len>

以上是將資料庫從伺服器移到瀏覽器--indexedDB基本操作封裝的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
HTML5:標準及其對Web開發的影響HTML5:標準及其對Web開發的影響Apr 27, 2025 am 12:12 AM

HTML5的核心特性包括語義化標籤、多媒體支持、離線存儲與本地存儲、表單增強。 1.語義化標籤如、等,提升代碼可讀性和SEO效果。 2.和標籤簡化多媒體嵌入。 3.離線存儲和本地存儲如ApplicationCache和LocalStorage,支持無網絡運行和數據存儲。 4.表單增強引入新輸入類型和驗證屬性,簡化處理和驗證。

H5代碼示例:實際應用和教程H5代碼示例:實際應用和教程Apr 25, 2025 am 12:10 AM

H5提供了多種新特性和功能,極大地增強了前端開發的能力。 1.多媒體支持:通過和元素嵌入媒體,無需插件。 2.畫布(Canvas):使用元素動態渲染2D圖形和動畫。 3.本地存儲:通過localStorage和sessionStorage實現數據持久化存儲,提升用戶體驗。

H5和HTML5之間的連接:相似性和差異H5和HTML5之間的連接:相似性和差異Apr 24, 2025 am 12:01 AM

H5和HTML5是不同的概念:HTML5是HTML的一個版本,包含新元素和API;H5是基於HTML5的移動應用開發框架。 HTML5通過瀏覽器解析和渲染代碼,H5應用則需要容器運行並通過JavaScript與原生代碼交互。

H5代碼的基礎:密鑰元素及其目的H5代碼的基礎:密鑰元素及其目的Apr 23, 2025 am 12:09 AM

HTML5的關鍵元素包括、、、、、等,用於構建現代網頁。 1.定義頭部內容,2.用於導航鏈接,3.表示獨立文章內容,4.組織頁面內容,5.展示側邊欄內容,6.定義頁腳,這些元素增強了網頁的結構和功能性。

HTML5和H5:了解常見用法HTML5和H5:了解常見用法Apr 22, 2025 am 12:01 AM

HTML5和H5沒有區別,H5是HTML5的簡稱。 1.HTML5是HTML的第五個版本,增強了網頁的多媒體和交互功能。 2.H5常用於指代基於HTML5的移動網頁或應用,適用於各種移動設備。

HTML5:現代網絡的基礎(H5)HTML5:現代網絡的基礎(H5)Apr 21, 2025 am 12:05 AM

HTML5是超文本標記語言的最新版本,由W3C標準化。 HTML5引入了新的語義化標籤、多媒體支持和表單增強,提升了網頁結構、用戶體驗和SEO效果。 HTML5引入了新的語義化標籤,如、、、等,使網頁結構更清晰,SEO效果更好。 HTML5支持多媒體元素和,無需第三方插件,提升了用戶體驗和加載速度。 HTML5增強了表單功能,引入了新的輸入類型如、等,提高了用戶體驗和表單驗證效率。

H5代碼:編寫清潔有效的HTML5H5代碼:編寫清潔有效的HTML5Apr 20, 2025 am 12:06 AM

如何寫出乾淨高效的HTML5代碼?答案是通過語義化標籤、結構化代碼、性能優化和避免常見錯誤。 1.使用語義化標籤如、等,提升代碼可讀性和SEO效果。 2.保持代碼結構化和可讀性,使用適當縮進和註釋。 3.優化性能,通過減少不必要的標籤、使用CDN和壓縮代碼。 4.避免常見錯誤,如標籤未閉合,確保代碼有效性。

H5:如何增強網絡上的用戶體驗H5:如何增強網絡上的用戶體驗Apr 19, 2025 am 12:08 AM

H5通過多媒體支持、離線存儲和性能優化提升網頁用戶體驗。 1)多媒體支持:H5的和元素簡化開發,提升用戶體驗。 2)離線存儲:WebStorage和IndexedDB允許離線使用,提升體驗。 3)性能優化:WebWorkers和元素優化性能,減少帶寬消耗。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能