HTML5-Web SQL database, html5-websql Database
Web SQL database API is not part of the HTML5 specification, but it is an independent specification that introduces a group of APIs that use SQL to operate the client database.
Core Methods
OpenDatabase-use an existing database or a new database to create a database object
Transaction-controls a transaction and executes the commit or rollback based on this situation.
ExecuteSql-execute the actual SQL statement
Open Database
// Use openDatabase () to open an existing database. If the database does not exist, a new database var db = openDatabase ('mydb', '1. 0', 'test db', 2*1024*1024 );
Description of the five parameters corresponding to the openDatabase () method:
The fifth parameter. The creation callback is called after the database is created.
Create a table
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)');});
Insert data
Var db = openDatabase ('mydb', '1. 0', 'test db', 2*1024*1024); DB. transaction (function (tx) {tx.exe cuteSql ('create table if not exists logs (id unique, log) '); tx.exe cuteSql ('insert into logs (id, log) VALUES (1, "blog") '); tx.exe cuteSql ('insert into logs (id, log) VALUES (2, "www.cnblogs.com ")');});
You can also use dynamic values to insert data.
// E_id and e_log are external variables. executeSql maps each entry in the array parameter "? "
Var db = openDatabase ('mydb', '1. 0', 'test db', 2*1024*1024); DB. transaction (function (tx) {tx.exe cuteSql ('create table if not exists logs (id unique, log) '); tx.exe cuteSql ('insert into logs (id, log) VALUES (?, ?) ', [E_id, e_log]) ;});
Read data
Var db = openDatabase ('mydb', '1. 0', 'test db', 2*1024*1024); DB. transaction (function (tx) {tx.exe cuteSql ('create table if not exists logs (id unique, log) '); tx.exe cuteSql ('insert into logs (id, log) VALUES (1, "blog") '); tx.exe cuteSql ('insert into logs (id, log) VALUES (2, "www.cnblogs.com")');}); db. transaction (function (tx) {tx.exe cuteSql ('select * FROM logs', [], function (tx, results) {var len = results. rows. length; msg = "<p> Number of query records:" + len + "</p>"; document. querySelector ('# status '). innerHTML + = msg; for (I = 0; I <len; I ++) {msg = "<p> <B>" + results. rows [I]. log + "</B> </p>" ;}}, null );});
Delete record
db.transaction(function (tx) { tx.executeSql('DELETE FROM LOGS WHERE id=1');});
Data deletion can also be dynamic.
db.transaction(function(tx) { tx.executeSql('DELETE FROM LOGS WHERE id=?', [id]);});
Update record
tx.executeSql("UPDATE CC SET logname='www.baidu.com' WHERE id=2");
Updating data can also be dynamic.
tx.executeSql("UPDATE CC SET logname='www.baidu.com' WHERE id=?", [id]);
Note:: Deletion and modification cannot be put in an executeSql statement with the table creation statement. It is best to write them separately.
The following are the databases created: