×

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

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.

Check Constraint in SQL

The Check Constraint in SQL is the rule or set of rules used to limit the data range that can be entered in a table column. Check constraint is used...

8 minutes read.

SQL SELECT AND Operator

This SQL tutorial explains and helps us understand how to use the AND Operator in the SELECT query with examples. The AND Operator is used to fetch the table’s records if...

2 minutes read.

How to delete a row in SQL

Introduction To delete or remove the unused/unwanted rows from a table, DELETE command is used in SQL.DELETE command removes the entire record from a table.The DELETE statement can delete one or...

6 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.

Nth highest salary

The most common and important question asked in interviews that how we can find the Nth highest salary in a table (2nd highest salary, 3rd highest salary, or Nth highest...

6 minutes read.

SQL SubQuery

The Sub-query in the SQL is the inner query placed or positioned inside another query, which is also known is the outer query. The inner query is embedded in the...

6 minutes read.

SQL Count

Structured Query Language Count() Function is used with Structured Query Language SELECT Statement. SQL Count() function returns the number of items that match the specified criteria in the SELECT statement. Count()...

2 minutes read.

SQL Alter Table

In Structured Query Language, if you want to add columns in an existing table, then modify the table, or delete columns from the table. All these operations are allowed only...

7 minutes read.

Difference between Delete, Drop and Truncate in SQL

What is the Delete command in SQL? In DML (Data Manipulation Language), we use the delete command that allows us to delete the some entries and modify the databases in SQL....

4 minutes read.

SET Operators in SQL

The operator used to join or combine two queries is none other than SET operators. Operators categorized into SET operators are as follows: UNION Operator.UNION ALL’ Operator.INTERSECT Operator.MINUS Operator. Rules to be...

8 minutes read.

What is SQL Injection?

Introduction to SQL Injection SQL injection is a vulnerability or a technique that might destroy the database of a website or a web application. It is one of the most widely...

4 minutes read.

SQL SELECT IN

SQL SELECT IN is a logical operator in Structured Query Language. It is used in SQL queries to reduce the use of multiple 'OR' operators. s The IN operator in SQL...

6 minutes read.

SQL Except

In SQL, we probably use the JOIN clause to receive the combined result from one or more than one table. But sometimes, we want a result that contains data from...

4 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 CONSTRAINTS

SQL Constraints specifies the rules/limitations/restrictions for data present in table. SQL Constraints are specified at the time of table creation or after table creation using ALTER command. There are two...

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 Queries

In a database, queries are used to request the result set of data from the table or action on the records. A Query can answer your simple or complicated question, perform...

5 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.

SQL INSERT Statement

In this tutorial, we will help you to understand and learn how to insert records to the table in SQL with the help of examples. SQL INSERT query is used to...

5 minutes read.