Hello Readers!
This blog is about how to use SQLite in Flex.
Before proceeding a brief introduction to SQLite.
SQLite is a relational database management system contained in a small C programming library,it is an embedded SQL database engine and a compact library.
It implements a self-contained, serverless, zero-configuration, transactional SQL database engine and the transactions are atomic, consistent, isolated, and durable (ACID) even after system crashes and power failures.There is no set up required and does not need to be configured before it is used.
And here goes the code!!
In this the "name" and "password" will insert into the table named "login" when a user click the button.
import flash.data.SQLConnection;
import flash.data.SQLMode;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.errors.SQLError;
import flash.events.EventDispatcher;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
import flash.filesystem.File;
import flash.net.Responder;
public class SQLHandler extends EventDispatcher
{
private var conn:SQLConnection;
public function SQLHandler()
{
createSQlConnection();
}
public function createSQlConnection():void
{
conn = new SQLConnection();
conn.addEventListener(SQLEvent.OPEN, onDatabaseOpen);
conn.addEventListener(SQLErrorEvent.ERROR,errorHandler);
var dbFile:File = File.applicationStorageDirectory.resolvePath("sampleDB.db");// name of the database
conn.openAsync(dbFile,SQLMode.CREATE);
}
private function onDatabaseOpen(event:SQLEvent):void
{
var sqlStat:SQLStatement = new SQLStatement();
sqlStat.sqlConnection=conn;
sqlStat.text= "CREATE TABLE IF NOT EXISTS login(id INTEGER PRIMARY KEY AUTOINCREMENT , Name TEXT ,Password INTEGER)";// name of the table and its fields
sqlStat.execute();
sqlStat.addEventListener(SQLEvent.RESULT,statResult);
sqlStat.addEventListener(SQLErrorEvent.ERROR, errorHandler);
}
public function errorHandler(evt:SQLErrorEvent):void
{
trace("error"+ evt.error.details);
}
public function statResult():void
{
var sqlQuery:String= "SELECT * FROM login";
executeQuery(sqlQuery);
}
private function executeQuery(sql:String):void
{
var sqlStat:SQLStatement = new SQLStatement();
sqlStat.sqlConnection=conn;
sqlStat.text = sql;
sqlStat.execute();
}
public function insertRecord():void
{
var sqlStat:SQLStatement = new SQLStatement();
sqlStat.sqlConnection=conn;
var query:String = "INSERT INTO login(Name,Password) values('" +name.text +"','" + password.text+ "')";
// here name and password are the ids of textInput Name and Password respectively
sqlStat.text= query;
sqlStat.execute();
}
}
if you find it useful do like and comment.. Happy reading (y)
1 Comment(s)