HTML5 Web SQL


The Web SQL Database API is not part of the HTML5 specification, but it is an independent specification that introduces a set of APIs for operating client databases using SQL.

If you are a web back-end programmer, it should be easy to understand SQL operations.

You can also refer to our SQL tutorial to learn more about database operations.

Web SQL database works in the latest versions of Safari, Chrome and Opera browsers.


Core methods

The following are the three core methods defined in the specification:

  1. openDatabase: This method Create a database object using an existing database or a new database.

  2. transaction: This method allows us to control a transaction and perform commit or rollback based on this situation.

  3. executeSql: This method is used to execute the actual SQL query.


Open the database

We can use the openDatabase() method to open an existing database. If the database does not exist, a new database will be created. The usage code is as follows:

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);

The five parameters corresponding to the openDatabase() method are explained:

  1. Database name

  2. Version number

  3. Description text

  4. Database size

  5. Create callback

The fifth parameter, the creation callback will be called after the database is created.


Execute query operation

Execute the operation using the database.transaction() function:

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)');
});

After the above statement is executed, a name will be created in the 'mydb' database is the table of LOGS.


Insert data

After executing the above create table statement, we can insert some data:

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, "php中文网")');
   tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "www.php.cn")');
});

We can also use dynamic values ​​to insert data:

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];
});

The e_id and e_log in the example are external variables, and executeSql will map each entry in the array parameter to "?".


Reading data

The following example demonstrates how to read data that already exists in the database:

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, "php中文网")');
   tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "www.php.cn")');
});

db.transaction(function (tx) {
   tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
      var len = results.rows.length, i;
      msg = "<p>查询记录条数: " + len + "</p>";
      document.querySelector('#status').innerHTML +=  msg;
	
      for (i = 0; i < len; i++){
         alert(results.rows.item(i).log );
      }
	
   }, null);
});

Complete example

Instance

<!DOCTYPE HTML>
<html>
   <head>
      <meta charset="UTF-8">
      <title>php中文网(php.cn)</title> 
      <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, "php中文网")');
            tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "www.php.cn")');
            msg = '<p>数据表已创建,且插入了两条数据。</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>查询记录条数: " + 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">状态信息</div>
   </body>
	
</html>

Run Instance»

Click the "Run Instance" button to view the online instance



Delete records

The format used to delete records is as follows:

db.transaction(function (tx) {
    tx.executeSql('DELETE FROM LOGS  WHERE id=1');
});

Deleting the specified data id can also be dynamic:

db.transaction(function(tx) {
    tx.executeSql('DELETE FROM LOGS WHERE id=?', [id]);
});

Update record

The format used to update the record is as follows:

db.transaction(function (tx) {
    tx.executeSql('UPDATE LOGS SET log=\'www.w3cschool.cc\' WHERE id=2');
});

Update the specified data id can also be dynamic:

db.transaction(function(tx) {
    tx.executeSql('UPDATE LOGS SET log=\'www.w3cschool.cc\' WHERE id=?', [id]);
});

Complete example

Instance

<!DOCTYPE HTML>
<html>
   <head>
      <meta charset="UTF-8">  
	   <title>php中文网(php.cn)</title> 
      <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, "php中文网")');
            tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "www.php.cn")');
            msg = '<p>数据表已创建,且插入了两条数据。</p>';
            document.querySelector('#status').innerHTML =  msg;
         });

         db.transaction(function (tx) {
              tx.executeSql('DELETE FROM LOGS  WHERE id=1');
              msg = '<p>删除 id 为 1 的记录。</p>';
              document.querySelector('#status').innerHTML =  msg;
         });

         db.transaction(function (tx) {
             tx.executeSql('UPDATE LOGS SET log=\'php.cn\' WHERE id=2');
              msg = '<p>更新 id 为 2 的记录。</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>查询记录条数: " + 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">状态信息</div>
   </body>
   
</html>

Run Instance»

Click the "Run Instance" button to view the online instance