Tuesday, October 20, 2009

HTML 5 and SQL Lite Sample Code

Here is a sample code that uses sqllite to store data locally in the browser that supports HTML5.

make sure to set this on the page event: body onload="createDatabase()"

html code... i replaced all <> characters to [ and ]...

sql statements:[br /] [textarea cols=50 rows=3 id="txtSQLStatement"][/textarea] [br /] [input type="button" id="Button1" value="execute" onclick="clickExecuteQuery()" /] [br /] [div id="status"][/div] [br /]

javascripts code:

var sampledb;
function createDatabase(){
try {
if (!window.openDatabase) {
alert('works on HTML5 only');
} else {
var name = 'sampledb';
var version = '1.0';
var description = 'Sample Database';
var maxSize = 32768; // in bytes
sampledb = openDatabase(name, version, description, maxSize);
}
} catch(e) {
// Error handling code goes here.
alert("Unknown error "+e+".");
return;
}
}


function executeSQL(sqlStatement)
{
sampledb.transaction(
function (transaction) {
transaction.executeSql(sqlStatement, [], nullDataHandler, errorHandler);
}
);
}

function executeQuery(sqlStatement)
{
sampledb.transaction(
function (transaction) {
transaction.executeSql(sqlStatement, [], dataHandler, errorHandler);
}
);
}

function nullDataHandler(transaction, results)
{
var d = new Date();
updateTransactionStatus("last statement: " + document.getElementById("txtSQLStatement").value + " ran at " + d.toUTCString());
}

function errorHandler(transaction, error)
{
// Error is a human-readable string.
updateTransactionStatus(' Error Message '+error.message+' (Code '+error.code+')');
return false;
}

function dataHandler(transaction, results)
{
// Handle the results
var string = "
results
";
for (var i=0; i}

var d = new Date();
updateTransactionStatus("last statement: " + document.getElementById("txtSQLStatement").value + " ran at " + d.toUTCString() + "
" + string);
//updateTransactionStatus(string);
}

function clickExecuteQuery(){
executeQuery(document.getElementById("txtSQLStatement").value);

}

function updateTransactionStatus(message){
document.getElementById("status").innerHTML = message;

}

Sample Statements

Create table
CREATE TABLE [Employee]( [ID] [integer] NOT NULL PRIMARY KEY AUTOINCREMENT, [EmployeeID] [int] NULL, [FirstName] [varchar](20) NULL, [LastName] [varchar](20) NULL)

Delete a table
Drop table employee

Insert Records
Insert into employee (employeeid,firstname,lastname) values(1,'z','a');

Update Records
Update employee set firstname='zaldy'

Remove Records
Delete from employee where firstname='zaldy'

Read Records
Select ID, FirstName, LastName from employee

No comments: