1、openDatabase:这个方法使用现有数据库或创建新数据库创建数据库对象。
2、transaction:这个方法允许我们根据情况控制事务提交或回滚。
3、executesql:这个方法用于执行真实的SQL查询。
打开数据库
openDatabase方法可以打开已经存在的数据库,不存在则创建:
var db = openDatabase('mydatabase', '2.0', my db', 2 * 1024);openDatabasek中五个参数分别为:数据库名、版本号、描述、数据库大小、创建回调。创建回调没有也可以创建数据库。
执行查询
database.transaction()函数用来查询,下面将在mydatabase数据库中创建表t1:
var db = openDatabase(' mydatabase ', '1.0', 'Test DB', 2 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS t1 (id unique, log)'); });
插入操作
var db = openDatabase('mydatabase', '2.0', my db', 2 * 1024); db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS t1 (id unique, log)'); tx.executeSql('INSERT INTO t1 (id, log) VALUES (1, "foobar")'); tx.executeSql('INSERT INTO t1 (id, log) VALUES (2, "logmsg")'); });在插入新记录时,我们还可以传递动态值,如:
var db = openDatabase(' mydatabase ', '2.0', 'my db', 2 * 1024); db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS t1 (id unique, log)'); tx.executeSql('INSERT INTO t1 (id,log) VALUES (?, ?'), [e_id, e_log]; //e_id和e_log是外部变量 });
读操作
如果要读取已经存在的记录,我们使用一个回调捕获结果,代码如下:
var db = openDatabase(mydatabase, '2.0', 'my db', 2*1024); db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS t1 (id unique, log)'); tx.executeSql('INSERT INTO t1 (id, log) VALUES (1, "foobar")'); tx.executeSql('INSERT INTO t1 (id, log) VALUES (2, "logmsg")'); }); db.transaction(function (tx) { tx.executeSql('SELECT * FROM t1, [], function (tx, results) { var len = results.rows.length, i; msg = "<p>Found rows: " + len + "</p>"; document.querySelector('#status').innerHTML += msg; for (i = 0; i < len; i++){ alert(results.rows.item(i).log ); } }, null); });
完整的示例
<!DOCTYPE HTML> <html> <head> <script type="text/javascript"> var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024); var msg; db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)'); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")'); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")'); msg = '<p>Log message created and row inserted.</p>'; document.querySelector('#status').innerHTML = msg; }); db.transaction(function (tx) { tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { var len = results.rows.length, i; msg = "<p>Found rows: " + len + "</p>"; document.querySelector('#status').innerHTML += msg; for (i = 0; i < len; i++){ msg = "<p><b>" + results.rows.item(i).log + "</b></p>"; document.querySelector('#status').innerHTML += msg; } }, null); }); </script> </head> <body> <div id="status" name="status">Status Message</div> </body> </html>下面是在最新版本的Safari或Opera浏览器中产生的输出结果。
Log message created and row inserted. Found rows: 2 foobar logmsg