<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Database API</title> </head> <body> <script type="text/javascript"> //"C:/Users/Administrator/AppData/Local/Google/Chrome/User Data/Default/databases/1"; if(window.openDatabase){ //如果 test数据库存在,则打开,否则会自动创建 var db = openDatabase("test", "1.0", "Database test", 1024 * 1024); //创建一个学生表 var sql = 'CREATE TABLE if not exists "student" ('+ '"_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,'+ '"name" TEXT NOT NULL,'+ '"age" TEXT,'+ '"mark" TEXT)'; //写入一条数据 var sql2 = 'insert into student (name,age,mark) values ("frog",1,"nice frog") '; //取出一行数据 var sql3 = 'select * from student'; //预处理语句的用法 var sql4 = 'insert into student (name,age,mark) values (:name,:age,:mark)'; /** * 预处理语句在php中也有类似的用法 * $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)"); * $stmt->bindParam(':name', $name); * $stmt->bindParam(':value', $value); */ var name = 'aron'; var age = 29; var mark = 'hello world'; exec(sql,function(rs){ //这里之所以要用回调, //是因为数据操作过程是异步的 exec(sql2,function(rs){ exec(sql3,function(rs){ console.log(rs.rows.item(0)) }) exec2(sql4,[name,age,mark]) }) }); //简单封装一个数据操作的方法 function exec(sql,callback){ db.transaction(function(tx){ //中间这个[],在预处理语句中绑值 tx.executeSql(sql,[],function(tx,rs){ //success callback && callback(rs); },function(tx,msg){ //error console.log(msg); }); }); } //支持变量邦定 function exec2(sql,para,callback){ para = para || []; db.transaction(function(tx){ tx.executeSql(sql,para,function(tx,rs){ //success callback && callback(rs); },function(tx,msg){ //error console.log(msg); }); }); } } </script> </body> </html> |