Tuesday 17 May 2011

How to use SQLite Database in Flex

package utils
{
    import event.SQLCustomEvent;
   
    import flash.data.SQLConnection;
    import flash.data.SQLMode;
    import flash.data.SQLResult;
    import flash.data.SQLStatement;
    import flash.events.EventDispatcher;
    import flash.events.SQLErrorEvent;
    import flash.events.SQLEvent;
    import flash.filesystem.File;
   
    import mx.collections.ArrayCollection;
    import mx.controls.Alert;
   
    public class SQLiteUtil extends EventDispatcher
    {
        private var userSQLAsyncConnection:SQLConnection = new SQLConnection();
        private var userSQLStatement:SQLStatement;
       
        public function SQLiteUtil()
        {
       
        }
       
        /**
         * This method will create a new connection to the database
         */
        public function getUserInformationDataSet():void
        {
            var userDatabase:File = File.desktopDirectory.resolvePath("USER_DATABASE.db");
           
            if(!userDatabase.exists)
            {
                Alert.show("Current project's database file not found in file system");
            }
            else
            {
                this.userSQLAsyncConnection = new SQLConnection();
                this.userSQLAsyncConnection.addEventListener(SQLEvent.OPEN, onDatabaseOpen);
                this.userSQLAsyncConnection.addEventListener(SQLErrorEvent.ERROR, onDatabaseConnError);
                this.userSQLAsyncConnection.addEventListener(SQLEvent.CLOSE, onDatabaseConnectionClose);
                this.userSQLAsyncConnection.openAsync(userDatabase, SQLMode.UPDATE);
            }
        }
       
        /**
         * This method will open the database and link the SQLStatment to our SQLConnection and creates a table in the database
         * @Event evt This is the SQLEvent
         */
        private function onDatabaseOpen(e:SQLEvent):void
        {
            //Alert.show("Dabase connection opened successfully");
            this.userSQLAsyncConnection.removeEventListener(SQLEvent.OPEN, onDatabaseOpen);
            this.userSQLAsyncConnection.removeEventListener(SQLErrorEvent.ERROR, onDatabaseConnError);
            executeSQLQuery(getSQLQuery());
        }
       
        /**
         * This method gets called when we recive an error  from sql connection or sql statment and displays the error in the alert
         * @parameter evt This is the SQLErrorEvent
         */
        private function onDatabaseConnError(e:SQLErrorEvent):void
        {
            Alert.show(e.toString());
        }
       
        /**
         * This method gets the SQL query required to fetch all the data from the database
         * @return: the SQL query required to get data from database
         */
        private function getSQLQuery():String
        {
            var sqlQuery:String = "SELECT * FROM USER_INFO;";
           
            return sqlQuery;
        }
       
        /**
         * This method executes the SQL query passed as an argument
         * This uses the asynchronous database connection to the SQLite database which is opened in the begining
         * @parameter sqlQueryArg: is the SQL query that needs to be executed
         */
        private function executeSQLQuery(sqlQueryArg:String):void
        {
            this.userSQLStatement = new SQLStatement();
            this.userSQLStatement.sqlConnection = this.userSQLAsyncConnection;
            this.userSQLStatement.text = sqlQueryArg;
            this.userSQLStatement.addEventListener(SQLEvent.RESULT, onResultFetch);
            this.userSQLStatement.addEventListener(SQLErrorEvent.ERROR, onResultFetchError);
            this.userSQLStatement.execute();
        }

        /**
         * This method will insert the usergiven data to the SQLite database
         * @parameter firstName, lastName, dateOfBirth, age, sex and qualification
         */
        public function setInformationInSQLiteDatabase(firstName:String, lastName:String, dateOfBirth:String, age:String, sex:String, qualification:String):void
        {
            openSQLConnection();
            this.userSQLStatement.text = "INSERT INTO USER_INFO (First_Name, Last_Name, DOB, Age, Sex, Qualification) VALUES('"+firstName+"','"+lastName+"','"+dateOfBirth+"','"+age+"','"+sex+"','"+qualification+"');";
            this.userSQLStatement.execute();
            closeConnection();
        }
       
        /**
         * This method will update the SQLite database with the new values
         * @parameter getOutput and conditionField
         */
        public function updateDatabase(getOutput:String,conditionField:int):void
        {
            openSQLConnection();
            this.userSQLStatement.text = "UPDATE USER_INFO SET "+getOutput+' WHERE ID="'+conditionField+'";';
            this.userSQLStatement.execute();
            closeConnection();
        }
       
        /**
         * This method will delete all the information present in the database
         */
        public function resetEntireDatabase():void
        {
            openSQLConnection();
            this.userSQLStatement.text = "DELETE FROM USER_INFO;";
            this.userSQLStatement.execute();
            closeConnection();
        }
       
        /**
         * This method will get the query result
         * @parameter evt This is the SQLEvent
         */
        private function onResultFetch(evt:SQLEvent):void
        {
            evt.currentTarget.removeEventListener(SQLEvent.RESULT, onResultFetch);
            evt.currentTarget.removeEventListener(SQLErrorEvent.ERROR, onResultFetchError);   
           
            var result:SQLResult = evt.currentTarget.getResult();
           
            var newCustomObj:SQLCustomEvent = new SQLCustomEvent(SQLCustomEvent.SQLCUSTOMEVENT,false,false);
            newCustomObj.dataSetResult = new ArrayCollection(result.data);
            dispatchEvent(newCustomObj);
        }
       
        /**
         * This method handles the error event that might occur during the fetching of data from the SQLite database
         * @parameter evt: is the SQLErrorEvent that will be dispatched when there is any error during the execution of SQL query
         */
        private function onResultFetchError(evt:SQLErrorEvent):void
        {
            Alert.show("Error during fetching values from DB : " + evt.error.toString());
            evt.currentTarget.removeEventListener(SQLEvent.RESULT, onResultFetch);
            evt.currentTarget.removeEventListener(SQLErrorEvent.ERROR, onResultFetchError);
        }
       
        /**
         * This method does the clean-up process. This should be called in the end when all the required processes are completed
         * This closes the asynchronous database connection to current project's database if the connection is open
         */
        private function closeConnection():void
        {
            if(this.userSQLAsyncConnection)
                this.userSQLAsyncConnection.close();
        }
       
        /**
         * This method will be executed when the database connection will be closed
         * evt: This is the SQLEvent
         */
        private function onDatabaseConnectionClose(evt:SQLEvent):void
        {
            Alert.show("Database connection closed successfully");
            this.userSQLAsyncConnection = null;
        }
       
        /**
         * This method will open the database file and creates a new sql connection
         */
        private function openSQLConnection():void
        {
            var userDatabase:File = File.desktopDirectory.resolvePath("USER_DATABASE.db");
           
            this.userSQLAsyncConnection.open(userDatabase);
            this.userSQLStatement = new SQLStatement();
            this.userSQLStatement.sqlConnection = this.userSQLAsyncConnection;   
        }
    }
}

No comments:

Post a Comment