×

WEB SQL

What is Web SQL?

In SQL we can create databases, read the data in the databases, insert the records into the databases, and delete the records from the databases. For storing the data and managing it, a web page API is used. This API (Application Programming Interface) is known as Web SQL.

Web SQL is an Application Programming Interface which helps developers in tackling some database operations from the client side.

Web SQL Database API does not come under HTML5 specification. Web SQL has a different specification.

Latest versions of Google Chrome, Opera, Safari, Android browsers accept the web SQL database.

This database is a deprecated web browser API specification for storing data in databases that can be queried using SQL variant.

Methods in Web SQL:

We have three main methods in Web SQL to access the data from the API.

openDatabase:

This function creates a new database. It  can also create the database object using the already existing database.

When we create a database, it can have four parameters:

  • Database name
  • Version number
  • Description
  • Size
  • Creation Callback

Transaction objects are obtained as result objects for callback. The result object has rows object, length. For obtaining individual rows, results.rows.item (i) should be used.

When we invoke openDatabase Method, it opens the specified database. If in case the database mentioned is absent, then this method creates a new database with the given database name.

NOTE: When the database is created, the creation callback is called internally.

Syntax:

var jtpdb = openDatabase (name of the database, version number, description,      size);

Example:

Now let’s create a database by running the below query.

var jtpdb = openDatabase (‘mydatabase’, ‘2.0’, ‘This is a company info database.’, 2*512*512);
if (! jtpdb)
{
	alert (‘Database is not created!”);
}
else
{
	var version = jtpdb. version;
}

So, this creates a database. If database is not created, then it gives an alert message.

executeSql:

This method is used to execute the SQL query. We use database.transaction () to execute a query. This function takes in, a single argument.

Example:

var db = openDatabase (‘mydatabase’, ‘2.0’, ‘Test_DB’, 2*512*512);
db.transaction (function (txc) {
	txc. executeSql (‘CRERATE TABLE IF NOT EXISTS LOBBY (ID unique, log)’);
});

This query creates a table LOBBY in ‘mydatabase’ database.

Transaction:

Performing some kind of operations on a database, is known as a transaction. Controlling the transactions is done, using rollback and commit functions.

Creating transactions:

From our database instance we can use transaction function to create transactions.

Syntax:

Mydb transaction (function (tx) {});

Mydb is an existing database and tx is a transaction that is used for upcoming operations.

Transaction will be rollbacked if any operation throws an error. These can be managed using transactions.

Steps of transaction:

We have a few steps for executing a transaction. These steps are assured to run asynchronously.

 These steps are initiated with a transaction callback, optionally a success callback, optionally an error callback, optionally a post flight operation, optionally a preflight operation along with a write/read mode or read only mode.

  1. We should open a new SQL transaction to the database. Then create a transaction object, specify the object with a mode. If the mode is read/write, the transaction should have an exclusive write lock for the entire database. If the mode selected is read-only mode, then the transaction should have a shared lock for the entire database.
  2. The user agent must wait for the appropriate lock to be available.
  3. If any error occurs, the jump over to the last step.
  4. For this instance of the transaction steps, if a prefight operation is defined then run that. If that fails, then we need to jump to the last step.
  5. If the callback raised an exception, jump to the last step.
  6. Perform the following steps for each queued up statement in the transaction with the oldest first, while there are any statements queued up in the transaction.
    • Execute the statement, in the context of the transaction.
    • Create a SQL Result Set, which represents the result of the statement.
    • Jump to the last step, if the callback has invoked an raised the exception.
    • Move to the next step, if no other issues raised.
  7. If success callback is not null, queue a task to invoke success callback.

The database task source is the task source for the above tasks.

Insert Operation:

For creating entries, we query the following statements.

var db = openDatabase (‘mydatabase’, ‘2.0’, ‘Test_DB’, 2*512*512);

var db = openDatabase (‘mydatabase’, ‘2.0’, ‘Test_DB’, 2*512*512);
jtpdb.transaction (function (tx) {
	tx.executeSq l(‘ CREATE TABLE IF NOT EXISTS CLASS (id unique, class)’);
	tx.executeSql (‘ INSERT INTO CLASS (id, class) VALUES(1, “hey”)’);
	tx.executeSql (‘ INSERT INTO CLASS (id, class) VALUES(2, “HELLO”)’);
var id = “1”
var String text = “heyy”
tx.executeSql (‘INSERT INTO CLASS (id, text) VALUES (?, ?)’, [id, text]);

So, in the last step, with the help of ‘?’ symbol we are retrieving the id and text values.

Read Operation:

By using insertion operation, we insert records into the database. So, after storing, if we want to retrive the records, we will use the read operation using callback function.

var db = openDatabase (‘mydatabase’, ‘2.0’, ‘Test_DB’, 2*512*512);
db.transaction (function (tx) {
	tx.executeSql (‘CREATE TABLE IF NOT EXISTS CLASS (id unique, class)’);
	tx.executeSq l(‘INSERT INTO CLASS (id, class) VALUES (1, “hey”)’);
  	   tx.executeSql (‘ INSERT INTO CLASS (id, class) VALUES(2, “HELLO”)’);
db.transaction ( function (tx) {
	tx.executeSql (‘SELECT * FROM CLASS’, [], function (tx, results) {
		var length = results.rows.length, i;
		message = “<p>Found rows: “ + length + “</p>”;
		document.querySelector (‘#status’). innerHTML += message;
		
		for (i = 0; I < length; i++)
		{
			alert (results.rows.item(i).class );
		}
	}, null ) ;
} ) ;

In the above query, we inserted the records with id’s 1 and 2 having text hey and hello respectively.

Next using the SQL keyword select, we are getting all the records from the CLASS database. Along with the records we are printing the length/ the number of records present in the CLASS, using rows.length function.


Related Topics

SQL Tutorial for Beginners

SQL tutorial provides basic and advanced concepts of Structured Query Language and how you deploy SQL to work with a relational database system. Our SQL tutorial is designed for beginners...

3 minutes read.

SQL SELECT LIKE Operator

The SQL SELECT LIKE Operator tutorial helps us understand how to use the LIKE operator in the SELECT query with examples. The SQL SELECT LIKE Operator retrieves the records from the...

4 minutes read.

SQL Topological Sorting

It is for Directed Acyclic Graph, which linearly describes the ordering of graphs. It is not possible for all graphs, it is possible for only Directed acyclic graphs. Applications of Topological...

3 minutes read.

SQL IN vs SQL EXISTS

SQL IN vs SQL EXISTS This article discusses in detail about the IN and the EXISTS operators in SQL. It is a common question between developers that what is the difference...

3 minutes read.

Types of SQL Commands

The Structured Query Language is used to deal with structured data. The data which are stored in the form of tables are structured data. These SQL commands store records or...

10 minutes read.

SQL CRUD Operation

In any computer language, CRUD operation is a foundation. CRUD operation rules are applied in databases as well. These operations are the basic operations used to perform with any database...

7 minutes read.

How to use the BETWEEN operator in SQL

In this entire SQL article, we will understand and learn about the BETWEEN operator concept and how to use it in SQL. What is the BETWEEN operator in SQL? The Between operator...

4 minutes read.

SQL CREATE TABLE

In SQL tutorial, we learned and created different databases. To stores data in databases, we need to create a table. To create the table, we need to use CREATE TABLE...

5 minutes read.

SQL UNION ALL Operator

This page has all the information about UNION ALL operator, which is used to join all the values from the SELECT queries. Similar records were not considered in the result in...

3 minutes read.

SQL SELECT SUM

The SQL Sum() function is an aggregate function in SQL that returns the total values of an expression. The expression may be numerical, or it may be an expression. Syntax: SELECT SUM(columnname)...

3 minutes read.

SQL ORDER BY

SQL ORDER BY The SQL ORDER BY clause is used to sort the data stored in tables in the database. The sorting can be done in an ascending way, descending way,...

5 minutes read.

How to compare date in SQL

In this section, we will learn about how dates can be compared in SQL. We can compare any random date with another date stored in a column of a table.This comparison...

4 minutes read.

SQL Cast Operator

While writing SQL queries, we can see many values which are to be converted into another datatype for accessing them. In SQL this conversion is generally done by CAST function. CAST...

4 minutes read.

How to Add Foreign Key in SQL?

How to Add Foreign Key in SQL Foreign key is an attribute or a set of attributes that references to primary key of same table or another table (relation). Foreign key creation along...

4 minutes read.

Truncate function in SQL

The TRUNCATE is a numeric function in SQL which truncates the number according to the particular decimal points. Syntax of TRUNCATE Function SELECT TRUNCATE(X, D) AS Alias_Name; In the TRUNCATE syntax, X...

4 minutes read.

SQL SELECT AVG

In this tutorial, we will learn about the aggregate function name avg() function concept in SQL with the help of examples. The AVG() function is one of the aggregate functions in...

3 minutes read.

SQL SELECT MIN

The SQL Min() function is an aggregate function in SQL. SQL Min() returns the minimum value of a given condition. The expression may be numerical, or it may be an expression. The syntax...

5 minutes read.

Difference between SQL and NoSQL

SQL vs. NoSQL | Difference between SQL and NoSQL Choosing a database is the most fundamental decision that needs to be decided before starting a task. Relational and non-relational databases are...

3 minutes read.

SQL TABLE

SQL TABLE Structured Query Language (SQL) is a relational database (RDBMS) where data is stored in the form of tables, that is, in rows and columns. These tables are known as...

3 minutes read.

SQL Auto Increment

As we all know, In SQL for unique identification, we assign a column with the primary key. But in some tables, we find difficult to differentiate a column as a...

5 minutes read.