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
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:
|
I’ve passed four arguments to the openDatabase method. These are:
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.
|
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) { |
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)
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Subject | Kudos |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
User | Count |
---|---|
7 | |
4 | |
4 | |
4 | |
4 | |
3 | |
3 | |
3 | |
2 | |
2 |