时间:2021-07-01 10:21:17 帮助过:15人阅读
openDatabase() 方法对应的五个参数说明:
第五个参数,创建回调会在创建数据库后被调用。
创建表
var db = openDatabase(‘mydb‘, ‘1.0‘, ‘Test DB‘, 2 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql(‘CREATE TABLE IF NOT EXISTS LOGS (id unique, log)‘); });
插入数据
var db = openDatabase(‘mydb‘, ‘1.0‘, ‘Test DB‘, 2 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql(‘CREATE TABLE IF NOT EXISTS LOGS (id unique, log)‘); tx.executeSql(‘INSERT INTO LOGS (id, log) VALUES (1, "博客园")‘); tx.executeSql(‘INSERT INTO LOGS (id, log) VALUES (2, "www.cnblogs.com")‘); });
也可以使用动态值插入数据
//e_id 和 e_log 是外部变量,executeSql 会映射数组参数中的每个条目给 "?"
var db = openDatabase(‘mydb‘, ‘1.0‘, ‘Test DB‘, 2 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql(‘CREATE TABLE IF NOT EXISTS LOGS (id unique, log)‘); tx.executeSql(‘INSERT INTO LOGS (id,log) VALUES (?, ?)‘, [e_id, e_log]); });
读取数据
var db = openDatabase(‘mydb‘, ‘1.0‘, ‘Test DB‘, 2 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql(‘CREATE TABLE IF NOT EXISTS LOGS (id unique, log)‘); tx.executeSql(‘INSERT INTO LOGS (id, log) VALUES (1, "博客园")‘); tx.executeSql(‘INSERT INTO LOGS (id, log) VALUES (2, "www.cnblogs.com")‘); }); db.transaction(function (tx) { tx.executeSql(‘SELECT * FROM LOGS‘, [], function (tx, results) { var len = results.rows.length; msg = "<p>查询记录条数: " + len + "</p>"; document.querySelector(‘#status‘).innerHTML += msg; for (i = 0; i < len; i++){ msg = "<p><b>" + results.rows[i].log + "</b></p>"; } }, null); });
删除记录
db.transaction(function (tx) { tx.executeSql(‘DELETE FROM LOGS WHERE id=1‘); });
删除数据也可以是动态的
db.transaction(function(tx) { tx.executeSql(‘DELETE FROM LOGS WHERE id=?‘, [id]); });
更新记录
tx.executeSql("UPDATE CC SET logname=‘www.baidu.com‘ WHERE id=2");
更新数据也可以是动态的
tx.executeSql("UPDATE CC SET logname=‘www.baidu.com‘ WHERE id=?", [id]);
注意:删除和修改不可以和建表语句放一个executeSql里,最好都分开写
以下是建好的数据库
HTML5-Web SQL数据库
标签:length 查询 where query let exists func value name