ADOBE/ ActionScript

[AS] adobe air moblie 액션스크립트 as3 Sqlite 다루기 관련

AlrepondTech 2020. 9. 20. 04:09
반응형

 

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://stackoverflow.com/questions/2262679/flash-cs4-sqlite

 

I'm looking for some information regarding using SQLITE with AIR in Flash CS4, I cannot find any good examples, they're all built for Flex (which I don't want to use). Can anyone give me some basic examples of how to do this with Flash CS4 or direct me to some code examples / tutorials? I cannot find any anywhere...

 

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

Here is an example from: http://www.flashmove.com/forum/showthread.php?t=34778

import flash.data.SQLResult;
import flash.filesystem.File;
import flash.data.SQLStatement;
import flash.data.SQLConnection;
import flash.data.SQLColumnSchema;
import flash.data.SQLTableSchema;
import flash.data.SQLSchemaResult;
import flash.events.SQLEvent;
import flash.events.SQLErrorEvent;
import flash.events.MouseEvent;


var sqlFile:File;
var sqlConn:SQLConnection;
var sqlStatement:SQLStatement;
init();
//- BUTTONS
go_mc.buttonMode = true;
go_mc.addEventListener(MouseEvent.MOUSE_DOWN, runQuery)
readDB_mc.buttonMode = true;
readDB_mc.addEventListener(MouseEvent.MOUSE_DOWN, readDB)

var exampleQuery:String = "INSERT INTO users (First_Name, Last_Name) VALUES ('Betty', 'Boil')";
query_txt.text = exampleQuery;


/**
 * Setup connection to db file
 */
function init():void {
    sqlConn = new SQLConnection();
    sqlConn.addEventListener(SQLEvent.OPEN, connOpenHandler);
    sqlConn.addEventListener(SQLErrorEvent.ERROR, errorHandler);

    sqlFile = new File(File.applicationDirectory.nativePath);
    sqlFile = sqlFile.resolvePath("users.db");
    feedback("Path to db file: "+sqlFile.nativePath);

    sqlConn.open(sqlFile);
}

function connOpenHandler(event:SQLEvent):void {
    feedback("DB Open");
    sqlStatement = new SQLStatement();
    sqlStatement.sqlConnection = sqlConn;
    sqlStatement.addEventListener(SQLErrorEvent.ERROR, errorHandler);

    dbScheme();
    readDB();
}

/**
 * Output the DB structure
 */
function dbScheme() {
    feedback("Schema...");
    sqlConn.loadSchema();
    var result:SQLSchemaResult = sqlConn.getSchemaResult();

    var table:SQLTableSchema = result.tables[0];
    //var column:SQLColumnSchema = table.columns[0]
    feedback("\tTable: "+table.name)
    for (var i=0; i<table.columns.length; i++) {
        feedback("\tColumn "+i+" - "+table.columns[i].name);
    }
}
/**
 * Output DB contents
 */
function readDB(e:Event = null) {
    sqlStatement.addEventListener(SQLEvent.RESULT, selectResultHandler);
    sqlStatement.text = "SELECT * FROM users";
    sqlStatement.execute();
}

/**
 * Run custom query
 */
function runQuery(e:MouseEvent) {
    var sqlQuery:String = query_txt.text;
    feedback("Query: "+sqlQuery);

    sqlStatement.addEventListener(SQLEvent.RESULT, queryResultHandler);
    sqlStatement.text = sqlQuery;
    sqlStatement.execute();
}
function queryResultHandler(e:SQLEvent){
    sqlStatement.removeEventListener(SQLEvent.RESULT, queryResultHandler);
    readDB();
}
/**
 * Handle readDB (SELECT) query
 */
function selectResultHandler(event:SQLEvent):void {
    feedback("Query Results...");
    sqlStatement.removeEventListener(SQLEvent.RESULT, selectResultHandler);

    var result:SQLResult = sqlStatement.getResult();

    if (result.data != null) {
        var numRows:int = result.data.length;
        for (var i:int = 0; i < numRows; i++) {
            var row:Object = result.data[i];
            feedback("\tid:"+ row.id+ ", name:"+ row.First_Name+" "+row.Last_Name);
        }
    }
}

function errorHandler(event:*):void {
    feedback("An error occured while executing the statement.");
}
function feedback(w:*) {
    output_txt.appendText(w+"\n");
    output_txt.verticalScrollPosition = output_txt.maxVerticalScrollPosition;
}

 

shareimprove this answer  

 

 

 

=================================

=================================

=================================

 

 

 

출처: http://stackoverflow.com/questions/31601858/how-connect-sqlite-with-adobe-air-for-android-using-flash-cs6-and-as3-language

 

 

I am developing a small game for Air Android in flash CS6, this game I'm programming object-oriented with classes written in AS3.

I want you to help me write a class that connects to SQLite from scratch, please!

I googled but only there information to FLEX or code for insert into frames (and i get lost because i don't know that libraries to import), it's not what I want.

I want to create the connection class to use in my class Main.

I hope I have your support, thank you.

Excuse my English but I speak Spanish.

---------------------------------------------------------------------------------------------------------------------------

 

You need 'Synchronous' or 'Asynchronous' sqlite connection ? You can see differences here: - Best practices for developing AIR Application with SQLite 
1. There is an example for 'async' connection :SQLConnection - you just have to modify and remove transactions part (if you do not need it). 
2. 'sync' is easy and i prefer this way 

 import flash.data.SQLConnection;
import flash.filesystem.File;
import flash.data.SQLMode; //if you use SQLMode: CREATE | UPDATE | READ
import flash.data.SQLStatement;
import flash.data.SQLResult;
import flash.errors.SQLError;

public class SQLiteConn 
{
    private var dbFile:File = new File("pathtofile");
    private var conn:SQLConnection;
    private var stmt:SQLStatement;
    private var arr:Array;


    public function SQLiteConn() 
    {
    }

    //open sqlite DB    
    public function openSQLite():Boolean {
        conn = new SQLConnection;
        if (dbFile.exists) {
            try {
                conn.open(dbFile);
                return true;
            }
            catch (error:SQLError) {
                trace(error.details, error.message);
            }
        }
        return false;
    }

    //execute statement and get result/s
    public function executeStatement(stmtText:String, param1:String, param2:String):Array {
        if (conn.connected) {   
            stmt = new SQLStatement();
            stmt.sqlConnection = con;
            stmt.text = stmtText;
            stmt.parameters[0] = param1;
            stmt.parameters[1] = param2;

            try {
                stmt.execute();
                var result:SQLResult = stmt.getResult();

                if (result.data != null) {
                    var total:int = result.data.length;
                    for (var i:int = 0; i < total; i++) {
                            row = result.data[i];
                            arr.push( { id:row.tablerowID } );
                    }
                }
                else {
                    arr.push({id: -1}); //no result/s
                }
            }
            catch (error:SQLError) {
                arr.push({id: -2}); //sqlite error
            }
        }
        else {
            arr.push({id: -2}); //no connection
        }
        return arr;

    }

    //close sqliteConnection
    public function closeSQLiteConn():void {
        if (conn.connected) {
            conn.close();
        }
    }
}

you can also 'dispatch event' from that class - it is your choise :)

 

 

 

=================================

=================================

=================================

 

 

 

 

반응형

 

728x90

 

 

 

출처: http://ntt.cc/2008/07/08/sqlite-example-for-adobe-air-working-with-local-sql-databases-with-source-code.html

 

The flollowing is a simplistic example that create a sqlite database, add, get, update and remove records from the “user” table.

Notice:
You might have wondered about this line:

sqlConnection.openAsync(dbFile);

.Asychnronous means that your code will have an event listener on the SQLConnection and an event handler for the response.

.Synchronous means that your application will make an “inline” call to SQLite where it performs the operation and then moves on as if it were any other line of actionscript code.This tutorial is using the asynchronous method. 

<?xml version=”1.0″ encoding=”utf-8″?>

<mx:WindowedApplication xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute”

        preinitialize=”openDatabaseConnection()”

        fontSize=”12″ backgroundColor=”#FFFFFF” width=”600″ height=”700″>

        <mx:Script>

                <![CDATA[

                        import flash.data.SQLConnection;

                        import flash.events.SQLErrorEvent;

                        import flash.events.SQLEvent;

                        import flash.filesystem.File;

                        private var conn:SQLConnection;

                        private var initComplete:Boolean = false;

                        private var sqlStat:SQLStatement;

 

                        public function openDatabaseConnection():void{

 

                        // create new sqlConnection

                        sqlConnection = new SQLConnection();

                        sqlConnection.addEventListener(SQLEvent.OPEN, onDatabaseOpen);

                        sqlConnection.addEventListener(SQLErrorEvent.ERROR, errorHandler);

 

                        // get currently dir

                        var dbFile:File = File.applicationStorageDirectory.resolvePath("sampleDB.db");

 

                        // open database,If the file doesn't exist yet, it will be created

                        sqlConnection.openAsync(dbFile);

                        }

 

                        // connect and init database/table

                        private function onDatabaseOpen(event:SQLEvent):void

                        {

                                // init sqlStatement object

                            sqlStat = new SQLStatement();

                                sqlStat.sqlConnection = conn;

                                var sql:String =         "CREATE TABLE IF NOT EXISTS user (" +

                                                                    "    id INTEGER PRIMARY KEY AUTOINCREMENT, " +

                                                                    "    name TEXT, " +

                                                                    "    password TEXT" +

                                                                    ")";

                                sqlStat.text = sql;

                                sqlStat.addEventListener(SQLEvent.RESULT, statResult);

                                sqlStat.addEventListener(SQLErrorEvent.ERROR, createError);

                                sqlStat.execute();

                        }

                        private function statResult(event:SQLEvent):void

                        {

                                // refresh data

                            var sqlresult:SQLResult = sqlStat.getResult();

                                if(sqlresult.data == null){

                                        getResult();

                                        return;

                                }

                                datafiled.dataProvider = sqlresult.data;

                        }

                        // get data

                        private function getResult():void{

                                var sqlquery:String = "SELECT * FROM user"

                                excuseUpdate(sqlquery);

                        }

                        private function createError(event:SQLErrorEvent):void

                        {

                            trace("Error code:", event.error.code);

                            trace("Details:", event.error.message);

                        }

                        private function errorHandler(event:SQLErrorEvent):void

                        {

                            trace("Error code:", event.error.code);

                            trace("Details:", event.error.message);

                        }

                        // update

                        private function excuseUpdate(sql:String):void{

                                sqlStat.text = sql;

                                sqlStat.execute();

                        }

                        // insert

                        private function insertemp():void{

                                var sqlupdate:String = "Insert into user(id,name,password) values('" +

                                                name.text +

                                                "','" +

                                                password.text  +

                                                "')";

                        debug.text+=sqlupdate+"\n"

                               excuseUpdate(sqlupdate)

                        }

                        // delete

                        private function deleteemp():void{

                                var sqldelete:String = "delete from user where id='" +

                                                datafiled.selectedItem.id +

                                                "'";

                                excuseUpdate(sqldelete);

                                debug.text+=sqldelete+"\n"

                        }

                ]]>

        </mx:Script>

        <mx:TextArea x=”21″ y=”10″ width=”402″ height=”179″ id=”debug”/>

        <mx:DataGrid x=”21″ y=”197″ id=”datafiled”>

                <mx:columns>

                        <mx:DataGridColumn headerText=”ID” dataField=”id”/>

                        <mx:DataGridColumn headerText=”name” dataField=”name”/>

                        <mx:DataGridColumn headerText=”password” dataField=”password”/>

                </mx:columns>

        </mx:DataGrid>

        <mx:Form x=”21″ y=”471″>

                <mx:FormItem label=”name”>

                        <mx:TextInput id=”name”/>

                </mx:FormItem>

                <mx:FormItem label=”password”>

                        <mx:TextInput id=”password”/>

                </mx:FormItem>

        </mx:Form>

        <mx:Button x=”300″ y=”503″ label=”add” click=”insertemp()”/>

        <mx:Button x=”300″ y=”533″ label=”delete” click=”deleteemp()”/>

</mx:WindowedApplication>

 

 

=================================

=================================

=================================

 

 

참고링크

 

http://www.slideshare.net/peterelst/introduction-to-sqlite-in-adobe-air-1627545

 

 

=================================

=================================

=================================

 

 

반응형