溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何將數(shù)據(jù)庫(kù)從服務(wù)器移到瀏覽器

發(fā)布時(shí)間:2021-09-17 10:57:55 來(lái)源:億速云 閱讀:178 作者:小新 欄目:web開(kāi)發(fā)

這篇文章給大家分享的是有關(guān)如何將數(shù)據(jù)庫(kù)從服務(wù)器移到瀏覽器的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。

一、鏈接數(shù)據(jù)庫(kù)

  indexedDB沒(méi)有創(chuàng)建數(shù)據(jù)庫(kù)的概念,你可以直接鏈接數(shù)據(jù)庫(kù),如果你鏈接的數(shù)據(jù)庫(kù)并不存在,那么會(huì)自動(dòng)的創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)??聪旅娴倪@個(gè)例子。

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><button type="" id='conbtn'>鏈接數(shù)據(jù)庫(kù)</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('數(shù)據(jù)庫(kù)鏈接成功!');
                success(e.target.result);            
            }
            dbConnect.onerror = function(e){
                console.log('數(shù)據(jù)庫(kù)鏈接失??!');
                error(e);
            }
            dbConnect.onupgradeneeded = function(e){
                success(e.target.result);
                let oldVersion = e.oldVersion;
                let newVersion = e.newVersion;
                console.log('數(shù)據(jù)庫(kù)更新成功,舊的版本號(hào)為:'+oldVersion+",新的版本號(hào)為:"+newVersion);
            }
   }
   window.onload=function(){
           let btn  = document.getElementById('conbtn');
           btn.onclick = function(){
               connectDB('haha',1,function(){
                   console.log('鏈接成功,或者更新成功回調(diào)函數(shù)');
               },function(){
                   console.log('鏈接失敗回調(diào)函數(shù)!')
               });
           }
   }</script></body></html>

  我點(diǎn)了兩次鏈接數(shù)據(jù)庫(kù),結(jié)果是這樣的。

如何將數(shù)據(jù)庫(kù)從服務(wù)器移到瀏覽器

  在Application的indexedDB中我們發(fā)現(xiàn)多了一個(gè)東西。

  如何將數(shù)據(jù)庫(kù)從服務(wù)器移到瀏覽器

  可以看到haha數(shù)據(jù)庫(kù)已經(jīng)成功建立了。

  indexedDB的open方法用來(lái)鏈接或者更新數(shù)據(jù)庫(kù),第一次創(chuàng)建也認(rèn)為是一次更新。第一個(gè)參數(shù)是數(shù)據(jù)庫(kù)的名字,第二個(gè)參數(shù)為版本號(hào)。第一次創(chuàng)建或者版本號(hào)發(fā)生改變時(shí)出發(fā)更新事件upgradeneeded,鏈接成功后出發(fā)success事件,鏈接出錯(cuò)時(shí)觸發(fā)error事件。

二、建表和索引

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><button type="" id='conbtn'>鏈接數(shù)據(jù)庫(kù)</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('數(shù)據(jù)庫(kù)鏈接成功!');
                success(e.target.result);            
            }
            dbConnect.onerror = function(e){
                console.log('數(shù)據(jù)庫(kù)鏈接失??!');
                error(e);
            }
            dbConnect.onupgradeneeded = function(e){
                update(e.target.result);
                let oldVersion = e.oldVersion;
                let newVersion = e.newVersion;
                console.log('數(shù)據(jù)庫(kù)更新成功,舊的版本號(hào)為:'+oldVersion+",新的版本號(hào)為:"+newVersion);
            }
   }       function createTable(idb,storeName,key,idxs){if(!idb){
            console.log(idb);return ;
        }if(!key || !idxs){
            console.log('參數(shù)錯(cuò)誤');return ;
        }if(!storeName){
            console.log('storeName必須');return ;
        }try{var store = idb.createObjectStore(storeName,key);
            console.log('數(shù)據(jù)庫(kù)存儲(chǔ)對(duì)象(table)創(chuàng)建成功');for(var i = 0;i<idxs.length;i++){var idx = idxs[i];
                store.createIndex(idx.indexName,idx.keyPath,idx.optionalParameters);
                    console.log('索引'+idx.indexName+'創(chuàng)建成功');
            }
        }catch(e){
            console.log('建表出現(xiàn)錯(cuò)誤');
            console.log(JSON.stringify(e))
        }
    }
   window.onload=function(){
           let btn  = document.getElementById('conbtn');
           btn.onclick = function(){
               connectDB('haha',1,                 function(idb){
                   console.log('鏈接成功,或者更新成功回調(diào)函數(shù)');
               },function(idb){                   createTable(idb,'test',{keyPath:'id',autoIncrement:true},[
                       {
                       indexName:'testIndex',
                     keyPath:'name',
                     optionalParameters:{
                         unique:true,
                         multiEntry:false }}]);                   
               },function(){
                   console.log('鏈接失敗回調(diào)函數(shù)!')
               });
           }
   }</script></body></html>

  我點(diǎn)了一下按鈕結(jié)果時(shí)這樣的。

  如何將數(shù)據(jù)庫(kù)從服務(wù)器移到瀏覽器

  如何將數(shù)據(jù)庫(kù)從服務(wù)器移到瀏覽器

  這里用到的兩個(gè)核心方法時(shí)createObjectStore,和createIndex,這兩個(gè)方法必須在數(shù)據(jù)庫(kù)發(fā)生更新的事件中執(zhí)行。

  createObjectStore方法可以理解成是創(chuàng)建表,接受第一個(gè)參數(shù)為一個(gè)字符串,表示表名,第二個(gè)參數(shù)是一個(gè)對(duì)象,指定主鍵相關(guān)的東西,{keyPath:'主鍵是哪個(gè)字段',autoIncrement:是否自增}。

  createIndex方法是創(chuàng)建索引的,接受三個(gè)參數(shù),第一個(gè)是一個(gè)字符串,表示索引的名字,第二個(gè)參數(shù)表示字段名(誰(shuí)的索引),第三個(gè)參數(shù)是個(gè)對(duì)象,具體自己查去。索引的作用是在查詢操作時(shí)可以用到,不詳講,自行g(shù)oogle吧。

三、添加數(shù)據(jù)

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><button type="" id='conbtn'>鏈接數(shù)據(jù)庫(kù)</button><button type="" id='add'>添加數(shù)據(jù)</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('數(shù)據(jù)庫(kù)鏈接成功!');
                success(e.target.result);            
            }
            dbConnect.onerror = function(e){
                console.log('數(shù)據(jù)庫(kù)鏈接失??!');
                error(e);
            }
            dbConnect.onupgradeneeded = function(e){
                update(e.target.result);
                let oldVersion = e.oldVersion;
                let newVersion = e.newVersion;
                console.log('數(shù)據(jù)庫(kù)更新成功,舊的版本號(hào)為:'+oldVersion+",新的版本號(hào)為:"+newVersion);
            }
   }       function createTable(idb,storeName,key,idxs){if(!idb){
            console.log(idb);return ;
        }if(!key || !idxs){
            console.log('參數(shù)錯(cuò)誤');return ;
        }if(!storeName){
            console.log('storeName必須');return ;
        }try{var store = idb.createObjectStore(storeName,key);
            console.log('數(shù)據(jù)庫(kù)存儲(chǔ)對(duì)象(table)創(chuàng)建成功');for(var i = 0;i<idxs.length;i++){var idx = idxs[i];
                store.createIndex(idx.indexName,idx.keyPath,idx.optionalParameters);
                    console.log('索引'+idx.indexName+'創(chuàng)建成功');
            }
        }catch(e){
            console.log('建表出現(xiàn)錯(cuò)誤');
            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+"個(gè)數(shù)據(jù)成功");
                }
                req.onerror = function(e){
                    console.log("添加第"+i+"個(gè)數(shù)據(jù)失敗");
                    console.log(JSON.stringify(e));
                }                            
            })(i)

        }
        ts.oncomplete = function(){
            console.log('添加數(shù)據(jù)事務(wù)結(jié)束!');
        }
    },function(){},function(){});

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

如何將數(shù)據(jù)庫(kù)從服務(wù)器移到瀏覽器

如何將數(shù)據(jù)庫(kù)從服務(wù)器移到瀏覽器

  比較神奇的是你在建表的時(shí)候不需要指定你的字段,再添加數(shù)據(jù)時(shí)可以隨便加。添加數(shù)據(jù)用到的是表對(duì)象的put方法,之前需要一個(gè)事務(wù),從事務(wù)調(diào)個(gè)方法拿到存儲(chǔ)對(duì)象(可以理解為表),具體看看例子就明白了。

四、查詢數(shù)據(jù)

Document鏈接數(shù)據(jù)庫(kù)添加數(shù)據(jù)查詢

如何將數(shù)據(jù)庫(kù)從服務(wù)器移到瀏覽器

  查詢操作主要用到了游標(biāo),這個(gè)說(shuō)起來(lái)還比較多,沒(méi)時(shí)間說(shuō)了,自行g(shù)oogle。還有很多的操作這里不講了。給一個(gè)我封裝的不是很好的簡(jiǎn)易庫(kù),僅供參考。

   一個(gè)簡(jiǎn)易庫(kù)。

(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:"",/**
     * 初始化數(shù)據(jù)庫(kù),創(chuàng)建表和建立鏈接
     * @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('數(shù)據(jù)庫(kù)鏈接成功!');                
        }
        dbConnect.onerror = function(e){
            console.log(e)
            self.log('數(shù)據(jù)庫(kù)鏈接失敗!');
        }
        dbConnect.onupgradeneeded = function(e){
            self.idb = e.target.result;var ts = e.target.transaction;var oldVersion = e.oldVersion;var newVersion = e.newVersion;
            self.log('數(shù)據(jù)庫(kù)更新成功,舊的版本號(hào)為:'+oldVersion+",新的版本號(hào)為:"+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)
                }
            }
        }
    },/**
     * 創(chuàng)建數(shù)據(jù)庫(kù)存儲(chǔ)對(duì)象(表)
     * @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('數(shù)據(jù)庫(kù)沒(méi)有鏈接');return ;
        }if(!key || !idxs){
            self.log('參數(shù)錯(cuò)誤');return ;
        }if(!storeName){
            self.log('storeName必須');return ;
        }try{var store = idb.createObjectStore(storeName,key);
            self.log('數(shù)據(jù)庫(kù)存儲(chǔ)對(duì)象(table)創(chuàng)建成功');for(var i = 0;i<idxs.length;i++){var idx = idxs[i];
                store.createIndex(idx.indexName,idx.keyPath,idx.optionalParameters);
            self.log('索引'+idx.indexName+'創(chuàng)建成功');
            }
        }catch(e){
            self.log('建表出現(xiàn)錯(cuò)誤');
            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+"個(gè)數(shù)據(jù)成功");
                    }
                    req.onerror = function(e){
                        self.log("添加第"+i+"個(gè)數(shù)據(jù)失敗");
                        self.log(JSON.stringify(e));
                    }                            
                })(i)

            }
            ts.oncomplete = function(){
                self.log('添加數(shù)據(jù)事務(wù)結(jié)束!');
            }
                    
        }

    },/**
     * [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("數(shù)據(jù)庫(kù)鏈接成功!");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("檢索出錯(cuò)")
                    }
                }else{//待寫(xiě)                }                        
            }

        }
    },/**
     * [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();
            }        
    },/**
     * 刪除數(shù)據(jù)庫(kù)
     * @param  {[type]} dbName [description]
     * @return {[type]}        [description]     */dropDatabase:function(dbName){this.indexedDB.deleteDatabase(dbName);this.log('成功刪除數(shù)據(jù)庫(kù):'+dbName);
    },/**
     * [log description]
     * @param  {[type]} msg [description]
     * @return {[type]}     [description]     */log:function(msg){
        console.log((new Date()).toTimeString()+":"+msg)
    }

    }

})(window);

五、使用indexedDB的優(yōu)缺點(diǎn)

  1、優(yōu)點(diǎn):可以將一些數(shù)據(jù)放到瀏覽器端,不用和服務(wù)器交互就可以實(shí)現(xiàn)一些功能,減輕服務(wù)器負(fù)擔(dān),加快響應(yīng)速度。

  2、缺點(diǎn):

  (1)不可靠:用戶可能刪處indexedDB,而且更換瀏覽器或者設(shè)備后這些數(shù)據(jù)就沒(méi)了。

  2)不便于數(shù)據(jù)采集:有很多時(shí)候?qū)?shù)據(jù)存到服務(wù)器是為了獲得一些數(shù)據(jù),如果放到瀏覽器端,這些數(shù)據(jù)比較難獲取。

 (3)無(wú)法共享:不同用戶沒(méi)辦法共享數(shù)據(jù),甚至?xí)r一個(gè)設(shè)備的不同瀏覽器也沒(méi)法共享。

  所以,是否適用indexedDB要進(jìn)行一下利弊權(quán)衡,不是有了indexedDB就啥也不管,一骨腦將數(shù)據(jù)放進(jìn)去。

感謝各位的閱讀!關(guān)于“如何將數(shù)據(jù)庫(kù)從服務(wù)器移到瀏覽器”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI