Showing posts with label html db. Show all posts
Showing posts with label html db. Show all posts

Sunday, 16 November 2014

Web SQL DB create, read, update and delete operations example

Here is the simplified example for web sql db create, read, update and delete operations:

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var db;
function createDatabase(dbName){
db = openDatabase(dbName, '1.0', 'Test DB', 2 * 1024 * 1024);
}

function createTable(tableName, arrFields){
db.transaction(function (tx) {
var fields = "";
for(f=0;f<arrFields.length;f++){
fields += arrFields[f] + ',';
}

fields = fields.substring(0, fields.length-1);

tx.executeSql('CREATE TABLE IF NOT EXISTS '+ tableName + ' (' + fields + ')');
});
}

function insertRecord(query){
db.transaction(function (tx) {
tx.executeSql(query);
});
}

function selectRecord(query, callBack){
var empArr = new Array();
db.transaction(function (tx) {
tx.executeSql(query, [], function (tx, results) {
var len = results.rows.length;

// Create the object of emp
for(i=0;i<len;i++){
var emp = {
id:results.rows.item(i).id,
name:results.rows.item(i).name,
salary:results.rows.item(i).salary
};

// Add objects to array
empArr[i] = emp;
}
callBack(empArr); // This is the callback
});
});
}

createDatabase('db_emp');
createTable('emp', ["id", "name", "salary"]);
insertRecord('INSERT INTO emp (id, name, salary) VALUES (1, "Rahul", 5000)');

// We are using callback in this method
selectRecord('select * from emp', function (results){
console.log(results);
});
</script>
</head>
<body>
</body>
</html>