针对HTML5 Web数据库的封装如下:
备注来自网络:
//自定义的数据库操作类 var Cls_websql = function(db_name,config){ //初始化变量 var cf= config?config:{}, cfg = { version: cf.version?cf.version:'1.0',desc: cf.desc?cf.desc:'数据库'+db_name,size: cf.size?cf.size:10*1024 }, log= function(msg, cat, src){ if (window['console'] !== undefined && console.log) { console[cat && console[cat] ? cat : 'log'](msg); } }, //还不成熟,sql中不能包含"?",例"select user where title like 'tb?'" formatSql= function(sql,data){ var count=0; return sql.replace(/(\?)/g, function(a,b){ return data[count++]; }); }, //初始化数据库 db= function(){ if(window['openDatabase'] !== undefined){ log("数据库连接成功"); return openDatabase(db_name, cfg.version , cfg.desc , cfg.size); }else{ log("数据库连接失败"); return null; } }(); this.db= db; //执行sql操作 this.execSql= function(sql,data,success,failure){ if(!db){ log("请先初始化数据库和表。"); return; } if(!data){ data= []; } if (success === undefined){ success = function(tx, results){ log("操作成功:"+formatSql(sql,data)); } } var errfun= toString.call(failure) === '[object Function]'? function(tx, err){ failure.call(this,tx,err,formatSql(sql,data)); } : function(tx, err){ log("操作失败! msg:"+err.message+" sql:"+formatSql(sql,data)); }; //真正执行sql的地方 db.transaction(function(tx){ try{ tx.executeSql(sql,data,success,errfun) }catch(e){ log("数据库执行失败:"+e.message); } }); }; };
使用如下:
<!DOCTYPE html> <html> <head> <title>测试 WebSQL Database</title> <meta charset="utf-8" /> </head> <body onload="init()"> <h1>Web SQL Database</h1> <div id="info"></div> <div id="result"></div> <button onclick="javascript:query();" value="查询"></button> </body> <script src="../js/WebSQLDatabase.js"></script> <script> function init() { var websql = new Cls_websql("stationList", {}); websql.execSql('CREATE TABLE IF NOT EXISTS SETS (key unique, value)'); } function query() { var websql = new Cls_websql("stationList", {}); websql.execSql("select * from sets ", [], function() { alert('success'); }, function() { alert('failure'); }) } </script> </html>