Home >Web Front-end >H5 Tutorial >Move the database from the server to the browser--indexedDB basic operation encapsulation
It is natural that the database belongs to the server, but sometimes the data may not need to be stored on the server, but the data is also recorded one by one. What should I do? Today I will lead you to experience a new feature of H5 - the charm of indexedDB. You can't help but sigh - incredible!
IndexedDB does not have the concept of creating a database. You can directly link to the database. If the database you link to does not exist, a database will be automatically created. Look at this example below.
<!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>
I clicked twice to connect to the database, and the result is this.
We found one more thing in the indexedDB of Application.
You can see that the haha database has been successfully established.
The open method of indexedDB is used to link or update the database. The first creation is also considered an update. The first parameter is the name of the database, and the second parameter is the version number. The update event upgradeneeded is triggered when it is created for the first time or when the version number changes. The success event is triggered after the link is successful. The error event is triggered when the link fails.
<!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>
I clicked the button and the result was like this.
The two core methods used here are createObjectStore and createIndex. These two methods must be used in the event that the database is updated. implement.
The createObjectStore method can be understood as creating a table. It accepts the first parameter as a string, indicating the table name, and the second parameter is an object, specifying things related to the primary key, {keyPath: 'Which is the primary key? Field',autoIncrement: whether to auto-increment}.
The createIndex method creates an index and accepts three parameters. The first is a string indicating the name of the index, the second parameter indicates the field name (whose index), and the third parameter is an object. , check it yourself. The function of the index is to be used during query operations. If you don’t know the details, just google it yourself.
<!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>
What’s amazing is that you don’t need to specify your fields when creating a table, and you can add them as you like when adding data. Adding data uses the put method of the table object. Previously, a transaction was required. Call a method from the transaction to get the storage object (which can be understood as a table). You will understand it by looking at the example.
Document链接数据库添加数据查询
Query operations mainly use cursors. There are many things to say about this, and I don’t have time to say it. , google by yourself. There are many more operations that I won’t go into here. Give me a simple library that I didn’t encapsulate very well, for reference only.
A simple library.
(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);
1. Advantages: You can put some data on the browser side, no need to By interacting with the server, you can implement some functions, reduce the burden on the server, and speed up the response.
2. Disadvantages:
(1) Unreliable: Users may delete indexedDB, and the data will be lost after changing browsers or devices.
2) Inconvenient for data collection: Many times, data is saved to the server to obtain some data. If it is placed on the browser, these data are more difficult to obtain.
(3) Unable to share: Different users cannot share data, and even different browsers on one device cannot share it.
Therefore, whether indexedDB is suitable requires weighing the pros and cons. It is not that with indexedDB, you just don’t care about anything and just put the data in.
The last two courses were designed and there were interviews. The article was written in a hurry. If there are any questions, please criticize and correct me. I'm looking for an internship recently. Dear friends, if what I write is good and the company is recruiting interns, you can give Daxiong a chance. Thank you!
The above is the detailed content of Move the database from the server to the browser--indexedDB basic operation encapsulation. For more information, please follow other related articles on the PHP Chinese website!