The Web SQL database API is not part of the HTML5 specification, but it is a separate specification that introduces a set of APIs that use SQL to manipulate the client database.
The following are the three core methods defined in the specification:
- OpenDatabase: This method creates a database object using an existing database or a newly created database.
- Transaction: This method allows us to control a transaction and execute commits or rollbacks based on this condition.
- ExecuteSQL: This method is used to execute the actual SQL query.
The OpenDatabase () method corresponds to five parameter descriptions:
① database name ② version number ③ description text ④ database size ⑤ Create callback
The code is as follows
var db = OpenDatabase (' mydb ', ' 1.0 ', ' Test db ', 2 * 1024 * 1024);
To perform an operation using the Database.transaction () function:
var db = OpenDatabase (' mydb ', ' 1.0 ', ' Test db ', 2 * 1024x768 * 1024x768);d b.transaction (function (TX) { tx.executesql (' CREATE TABLE IF not EXISTS LOGS (id unique, log) ');});
This will insert a logs table in the MyDB
After executing the above created table statement, we can insert some data:
var db = OpenDatabase (' mydb ', ' 1.0 ', ' Test db ', 2 * 1024x768 * 1024x768);d b.transaction (function (TX) { tx.executesql (' CREATE TABLE IF not EXISTS LOGS (id unique, log) '); Tx.executesql (' INSERT into LOGS (ID, log) VALUES (1, "La la La) '); Tx.executesql (' INSERT into LOGS (ID, log) VALUES (2, ' www.baidu.com ') ');});
How to read data that already exists in the database:
var db = OpenDatabase (' mydb ', ' 1.0 ', ' Test db ', 2 * 1024x768 * 1024x768); Db.transaction (function (TX) {tx.executesql (' CREA TE TABLE IF not EXISTS LOGS (id unique, log) '); Tx.executesql (' INSERT into LOGS (ID, log) VALUES (1, "rookie Tutorial"); Tx.executesql (' INSERT into LOGS (ID, log) VALUES (2, ' www.runoob.com ') ');}); Db.transaction (Function (TX) {tx.executesql (' SELECT * from LOGS ', [], function (TX, results) {var len = RESULTS.R Ows.length, I; msg = "<P>Query record number: "+ len +"</P>"; Document.queryselector (' #status '). InnerHTML + + msg; for (i = 0; I<Len; i++) {Alert (Results.rows.item (i). log); }}, null);});
HTML5 Web SQL Database operations