찾다
웹 프론트엔드H5 튜토리얼서버에서 브라우저로 데이터베이스 이동 - indexedDB 기본 작업 캡슐화

서버에서 브라우저로 데이터베이스 이동 - indexedDB 기본 작업 캡슐화

Jun 23, 2017 pm 02:04 PM
firefoxiewebkit데이터 베이스섬기는 사람브라우저

 데이터베이스는 서버에 속해 있는 것이 당연합니다. 그런데 데이터를 서버에 저장할 필요가 없는데 데이터가 하나씩 기록되는 경우도 있습니다. 오늘은 H5의 새로운 기능인 indexedDB의 매력을 소개하겠습니다. 당신은 한숨을 쉬지 않을 수 없습니다. 놀랍습니다!

1. 데이터베이스 연결

  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>

 데이터베이스 연결을 위해 두번 클릭했는데 결과는 이렇습니다.

애플리케이션의 indexedDB에서 한 가지를 더 발견했습니다.

 

  ㅎㅎ 데이터베이스가 성공적으로 구축된 것을 볼 수 있습니다.

 indexedDB의 개방형 방식은 데이터베이스를 연결하거나 업데이트하는 데 사용됩니다. 첫 번째 매개변수는 데이터베이스 이름이고, 두 번째 매개변수는 버전 번호입니다. updateneeded 업데이트 이벤트는 처음 생성되거나 버전 번호가 변경될 때 발생합니다. 성공 이벤트는 링크가 성공한 후 발생합니다. 오류 이벤트는 링크가 실패할 때 발생합니다.

2. 테이블과 인덱스 생성하기

 

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에 문의하십시오.

3. 데이터 추가

 

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 메소드를 사용합니다. 이전에는 트랜잭션에서 메소드를 호출하여 스토리지 객체(테이블로 이해 가능)를 가져옵니다.

4. Query data

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

쿼리 작업은 주로 커서를 사용하는데, 얘기할 시간이 없어서 제가 직접 구글링해보겠습니다. 여기서 다루지 않을 작업이 더 많이 있습니다. 참조용으로만 잘 캡슐화하지 않은 간단한 라이브러리를 제공하십시오.

  간단한 라이브러리.

(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></len>

5. indexedDB 사용의 장점과 단점

1. 장점: 브라우저 측에 일부 데이터를 넣을 수 있고, 서버와 상호작용 없이 일부 기능을 구현할 수 있어 서버의 부하를 줄일 수 있다. , 응답 속도를 높입니다.

 2. 단점:

  (1) 신뢰할 수 없음: 사용자가 indexedDB를 삭제할 수 있으며, 브라우저나 장치를 변경하면 데이터가 손실됩니다.

 2) 데이터 수집이 불편함: 일부 데이터를 얻기 위해 데이터를 서버에 저장하는 경우가 많습니다. 브라우저에 배치하면 이러한 데이터를 얻기가 더 어렵습니다.

  (3) 공유 불가: 서로 다른 사용자가 데이터를 공유할 수 없으며, 한 기기의 서로 다른 브라우저에서도 데이터를 공유할 수 없습니다.

따라서 indexedDB가 적합한지 여부는 장단점을 따져볼 필요가 있습니다. 그렇다고 indexedDB를 사용하면 아무것도 신경 쓰지 않고 데이터만 넣는다는 의미는 아닙니다.

 

 지난 두 코스는 기획되었고 인터뷰도 있었습니다. 기사는 급하게 작성되었습니다. 궁금한 점이 있으면 비판하고 정정해 주세요. 저는 최근 인턴십을 찾고 있습니다. 친구 여러분, 제가 쓴 내용이 좋고 회사에서 인턴을 모집하고 있다면 Daxiong에게 기회를 주세요.

위 내용은 서버에서 브라우저로 데이터베이스 이동 - indexedDB 기본 작업 캡슐화의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
H5 : 웹에서 사용자 경험을 향상시키는 방법H5 : 웹에서 사용자 경험을 향상시키는 방법Apr 19, 2025 am 12:08 AM

H5는 멀티미디어 지원, 오프라인 스토리지 및 성능 최적화로 웹 사용자 경험을 향상시킵니다. 1) 멀티미디어 지원 : H5 및 요소는 개발을 단순화하고 사용자 경험을 향상시킵니다. 2) 오프라인 스토리지 : WebStorage 및 IndexedDB는 오프라인으로 사용하여 경험을 향상시킵니다. 3) 성능 최적화 : 웹 워즈 및 요소는 성능을 최적화하여 대역폭 소비를 줄입니다.

H5 코드 해체 : 태그, 요소 및 속성H5 코드 해체 : 태그, 요소 및 속성Apr 18, 2025 am 12:06 AM

HTML5 코드는 태그, 요소 및 속성으로 구성됩니다. 1. 태그는 컨텐츠 유형을 정의하고 다음과 같은 각도 브래킷으로 둘러싸여 있습니다. 2. 요소는 컨텐츠와 같은 시작 태그, 내용 및 엔드 태그로 구성됩니다. 3. 속성 시작 태그에서 키 값 쌍을 정의하고 기능을 향상시킵니다. 웹 구조를 구축하기위한 기본 단위입니다.

H5 코드 이해 : HTML5의 기본 사항H5 코드 이해 : HTML5의 기본 사항Apr 17, 2025 am 12:08 AM

HTML5는 현대적인 웹 페이지를 구축하는 핵심 기술로 많은 새로운 요소와 기능을 제공합니다. 1. HTML5는 웹 페이지 구조 및 SEO를 향상시키는 의미 론적 요소를 소개합니다. 2. 멀티미디어 요소를 지원하고 플러그인없이 미디어를 포함시킵니다. 3. 양식은 새로운 입력 유형 및 검증 속성을 향상시켜 검증 프로세스를 단순화합니다. 4. 웹 페이지 성능 및 사용자 경험을 향상시키기 위해 오프라인 및 로컬 스토리지 기능을 제공합니다.

H5 코드 : 웹 개발자를위한 모범 사례H5 코드 : 웹 개발자를위한 모범 사례Apr 16, 2025 am 12:14 AM

H5 코드에 대한 모범 사례는 다음과 같습니다. 1. 올바른 문서 선언 및 문자 인코딩 사용; 2. 시맨틱 태그를 사용하십시오. 3. HTTP 요청을 줄입니다. 4. 비동기 부하 사용; 5. 이미지 최적화. 이러한 관행은 웹 페이지의 효율성, 유지 관리 및 사용자 경험을 향상시킬 수 있습니다.

H5 : 웹 표준 및 기술의 발전H5 : 웹 표준 및 기술의 발전Apr 15, 2025 am 12:12 AM

웹 표준과 기술은 현재까지 HTML4, CSS2 및 간단한 JavaScript에서 발전했으며 중대한 개발을 거쳤습니다. 1) HTML5는 캔버스 및 웹 스토리지와 같은 API를 도입하여 웹 응용 프로그램의 복잡성과 상호 작용을 향상시킵니다. 2) CSS3은 애니메이션 및 전환 기능을 추가하여 페이지를보다 효과적으로 만듭니다. 3) JavaScript는 화살표 기능 및 클래스와 같은 Node.js 및 ES6의 최신 구문을 통해 개발 효율 및 코드 가독성을 향상시킵니다. 이러한 변경으로 인해 웹 애플리케이션의 성능 최적화 및 모범 사례의 개발이 촉진되었습니다.

H5는 HTML5의 속기입니까? 세부 사항을 탐색합니다H5는 HTML5의 속기입니까? 세부 사항을 탐색합니다Apr 14, 2025 am 12:05 AM

H5는 HTML5의 약어 일뿐 만 아니라 더 넓은 현대 웹 개발 기술 생태계를 나타냅니다. 1. H5는 HTML5, CSS3, JavaScript 및 관련 API 및 기술을 포함합니다. 2. 그것은 더 풍부하고 대화식이며 부드러운 사용자 경험을 제공하며 여러 장치에서 원활하게 실행할 수 있습니다. 3. H5 기술 스택을 사용하여 반응 형 웹 페이지와 복잡한 대화식 기능을 만들 수 있습니다.

H5 및 HTML5 : 웹 개발에 일반적으로 사용되는 용어H5 및 HTML5 : 웹 개발에 일반적으로 사용되는 용어Apr 13, 2025 am 12:01 AM

H5 및 HTML5는 동일한 것을, 즉 html5를 나타냅니다. HTML5는 HTML의 다섯 번째 버전으로 시맨틱 태그, 멀티미디어 지원, 캔버스 및 그래픽, 오프라인 스토리지 및 로컬 스토리지와 같은 새로운 기능을 제공하여 웹 페이지의 표현성 및 상호 작용성을 향상시킵니다.

H5는 무엇을 언급합니까? 맥락 탐색H5는 무엇을 언급합니까? 맥락 탐색Apr 12, 2025 am 12:03 AM

h5referstohtml5, apivotaltechnologyinwebdevelopment.1) html5introducesnewelements 및 dynamicwebapplications.2) itsupp ortsmultimediawithoutplugins, enovannangeserexperienceacrossdevices.3) SemanticLementsImproveContentsTructUreAndSeo.4) H5'Srespo

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경