Introduction
Web SQL is very interesting feature, even though it isn't part of the HTML 5 specification. But it is a separate specification and it can still help for developing web applications. Web SQL is used to manipulate a client-side database. Since I am saying that it is good to use, there is a disclaimer for its use; it is risky because it stores data at the client side, not on the server side. So always remember, don't store information sensitive to the server inside it.
Note
A Web SQL database only works in the latest versions of Safari, Google Chrome and Opera browsers.
Core Methods of Web SQL
The following are the 3 core methods of Web SQL that I will cover in this article:
- openDatabase
- transaction
- executeSql
Creating and Opening Databases
Using the openDatabase method you can create an object for the database. If the database doesn't exist then it will be created and then an object for that database will be created. You also don't need to worry about closing the connection with the database.
To create and open the database you need to use the following syntax.
var dbObj = OpenDatabase('[Database_Name]', '[Version_Number]', '[Text_Description]', '[size]', '[Creation_Callback]')
Example
The following example describes how to create a database or its object.
- First, create a button in your HTML 5 page as in the following:
- <!DOCTYPE html>
- <html>
- <head>
- <title>Open Database</title>
- </head>
- <body>
- <button id="btnCreateDB">Create Database</button>
- </body>
- </html>
-
Now create a JavaScript function to create the database as in the following:
- function CreateDB() {
- var Database_Name = 'MyDatabase';
- var Version = 1.0;
- var Text_Description = 'My First Web-SQL Example';
- var Database_Size = 2 * 1024 * 1024;
- var dbObj = openDatabase(Database_Name, Version, Text_Description, Database_Size, OnSuccessCreate());
- }
- function OnSuccessCreate() {
- alert('Database Created Sucessfully');
- }
-
Now bind this JavaScript function to the onclick event of the btnCreateDB button. The complete code is given below:
- <!DOCTYPE html>
- <html>
- <head>
- <title>Open DataBase</title>
- <script>
- function CreateDB() {
- var Database_Name = 'MyDatabase';
- var Version = 1.0;
- var Text_Description = 'My First Web-SQL Example';
- var Database_Size = 2 * 1024 * 1024;
- var dbObj = openDatabase(Database_Name, Version, Text_Description, Database_Size, OnSuccessCreate());
- }
- function OnSuccessCreate() {
- alert('Database Created Sucessfully');
- }
- </script>
- </head>
- <body>
- <button id="btn1" onclick="CreateDB()">Create Database</button>
- </body>
- </html>
-
Now open this file, I am opening it in Google Chrome. By default the output will be:
-
Now press the F12 function key and open the Google Chrome developer tool and open the Resource tab where you will get a Web SQL database.
-
Now click on the Create Database button and you will get the following output.
And inside the developer tool you will get the database.
Since you saw how to create and open the database in Web SQL, so by using the openDatabase function we can create a database in Web SQL and open the database. There are 5 parameters that are accepted by this openDatabase function that are:
- Database name: This argument provides the name of the database that is mandatory to be provided, otherwise you will get an exception.
- Version number: Version number is also required; some database may be in version 2.0 and may be in 1.0 so if you know the version number of the database then only you can open it.
- Text description: This argument describes the database and provides information about the database.
- Size of database: This argument decides the size of the database.
- Creation callback: This argument is optional, if you do not provide any value then the database will also be created but if you want to perform some action after creation of the database then you can use this, so if the database is created successfully then this work will be done.
Transactions
After opening our database we can create transactions. This provides the rollback and commit facility. This means inside the transaction we can fire more than one query. If a transaction fails at any point of time or a query has an error then it will be rolled back including all the queries and if all the queries successfully executed then the transaction will be committed.
A transaction is the same as a function that contains more than one query statement.
Example
- function CreateDB() {
- var Database_Name = 'MyDatabase';
- var Version = 1.0;
- var Text_Description = 'My First Web-SQL Example';
- var Database_Size = 2 * 1024 * 1024;
- var dbObj = openDatabase(Database_Name, Version, Text_Description, Database_Size);
- dbObj.transaction(function (tx) {
-
-
- });
- }
executeSql
This method performs a very important role for the Web SQL database. This method is used to execute read and write statements which include SQL injection projection and provides a call back method to process the result of any queries. Once if we have a transaction object then we can call the executeSql method.
Example
The following example also explains how to create a table in Web SQL.
- <!DOCTYPE html>
- <html>
- <head>
- <title>Open DataBase</title>
- <script>
- function CreateDB() {
- var Database_Name = 'MyDatabase';
- var Version = 1.0;
- var Text_Description = 'My First Web-SQL Example';
- var Database_Size = 2 * 1024 * 1024;
- var dbObj = openDatabase(Database_Name, Version, Text_Description, Database_Size);
- dbObj.transaction(function (tx) {
- tx.executeSql('CREATE TABLE IF NOT EXISTS Employee_Table (id unique, Name, Location)');
- });
- }
- </script>
- </head>
- <body>
- <button id="Create_DB_n_Table" onclick="CreateDB()">Create Database & Table</button>
- </body>
- </html>
Output of the preceding Example
- When the page is loaded:
- If you then open the developer tool of Google Chrome then you will get the following output:
- After clicking on the button:
How to inset the data into Web SQL table
How to read the data from the web SQL
The following example will explain how to read the data from the Web SQL.
- <!DOCTYPE html>
- <html>
- <head>
- <title>Open DataBase</title>
- <script>
- var Database_Name = 'MyDatabase';
- var Version = 1.0;
- var Text_Description = 'My First Web-SQL Example';
- var Database_Size = 2 * 1024 * 1024;
- var dbObj = openDatabase(Database_Name, Version, Text_Description, Database_Size);
- dbObj.transaction(function (tx) {
- tx.executeSql('CREATE TABLE IF NOT EXISTS Employee_Table (id unique, Name, Location)');
- });
-
- function Insert() {
- var id = document.getElementById("tbID").value;
- var name = document.getElementById("tbName").value;
- var location = document.getElementById("tbLocation").value;
- dbObj.transaction(function (tx) {
- tx.executeSql('insert into Employee_Table(id, Name, Location) values(' + id + ',"' + name + '","' + location + '")');
- });
- }
- dbObj.transaction(function (tx) {
- tx.executeSql('SELECT * FROM Employee_Table', [], function (tx, results) {
- var len = results.rows.length, i;
- var str = '';
- for (i = 0; i < len; i++) {
- str += "<tr>";
- str += "<td>" + results.rows.item(i).id + "</td>";
- str += "<td>" + results.rows.item(i).Name + "</td>";
- str += "<td>" + results.rows.item(i).Location + "</td>";
- str += "</tr>";
- document.getElementById("tblGrid").innerHTML += str;
- str = '';
- }
- }, null);
- });
- </script>
- </head>
- <body>
- <p id="hh"></p>
- <form id="frm1">
- <table>
- <tr>
- <td>ID:</td>
- <td><input type="text" id="tbID" /></td>
- </tr>
- <tr>
- <td>Name:</td>
- <td><input type="text" id="tbName" /></td>
- </tr>
- <tr>
- <td>Location:</td>
- <td><input type="text" id="tbLocation" /></td>
- </tr>
- <tr>
- <td><button id="btnInsert" onclick="Insert()">Insert</button></td>
- </tr>
- </table>
- </form>
- <table id="tblGrid" cellpadding="10px" cellspacing="0" border="1">
- <tr style="background-color:black;color:white;font-size:18px;">
- <td>
- ID
- </td>
- <td>
- Name
- </td>
- <td>
- Location
- </td>
- </tr>
- </table>
- </body>
- </html>
As with SQL Server, by using a select query you can read the data from the Web SQL.
The following is the output of the code above:
Note that Web SQL Databases were on the W3C Recommendation track but specification work has stopped because all interested implementors use Sqlite and multiple independent implementations are necessary for a standard.