Skip to Content

Using HTML5, web pages can store data locally within the user’s browser.

WebSQL database defines an API for storing data in databases that can be queried using a variant of SQL.

There are three core methods:

1. openDatabase

2. transaction

3. executeSql

Creating and Opening Databases(openDatabase)

If you try to open a database that doesn’t exist, the API will create it on the fly for you using openDatabase method.

To create and open a database, use the following code:

var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);


I’ve passed four arguments to the openDatabase method. These are:

  1. Database name
  2. Version number
  3. Text description
  4. Estimated size of database

Transactions(transaction)

Once we have opened our database, we can create transactions. The transactions give us the ability to rollback the query transactions.

i.e., if a transaction — which could contain one or more SQL statements — fails (either the SQL or the code in the transaction), the updates to the database are never committed — i.e. it’s as if the transaction never happened.

in single word we can say, transaction obeys, ATOMICITY property of DBMS.

There are also error and success callbacks on the transaction, so you can manage errors, but it’s important to understand that transactions have the ability to rollback changes.

db.transaction(function (query) {
  // write SQL statements here using the "query" object
});

executeSql

executeSql is used for both read and write statements, includes SQL injection projection, and provides a callback method to process the results of any queries you may have written.

db.transaction(function (query) {
  query
.executeSql('CREATE TABLE foo (id unique, text)');
});

Sample HTML Code:-


<!doctype html>

<html>

<head>

<script>

//Create DB Connection

var db =openDatabase(‘mydb’,’1.0′,’testdb’,1024);

//Create table under the above DB

db.transaction(function(query){

query.executeSql(‘create table if not exists user(id unique, usesr, passwd)’);

});

//Insert values to the table

db.transaction(function(query){

query.executeSql(‘insert into user values (1,”jai”,”pass”)’);

});

//Get stored values from the table

db.transaction(function(query){

query.executeSql(‘select * from user’,[],function(u,results){

document.write(‘lenght => ‘+results.rows.length)

});

});

</script>

</head>

</html>

Output:-(Executed in Google Chrome)

WebSQL.png

To report this post you need to login first.

5 Comments

You must be Logged on to comment or reply to a post.

    1. Jaya Bharath S Post author

      Hi Thomas,

      Thanks for bring it up.

      IndexDB in HTML5 would replace this browser compatiblity issue.

      I am seeing most interesting stuffs with HTML5.. I will share my experience as i learn.

      Thanks.

      Bharath. S

      (0) 

Leave a Reply