Home >
In the last tutorial, I examined some additional techniques for querying an existing database. Today I want to explain how you create a database and create a table inside of that database.. If you are good with SQL and have followed along with this series, this concept will work as expected.
Creating Databases
I briefly touch on creating databases in a previous tutorial. The concept is very similar to working with a pre-populated database. Just as with a pre-populated database you will need to create an instance of the File class that points to a file. If that file does not exist, then the database will be created when the open or openAsync methods are called.
...
// Create an instance of the SQLConnection Class
var conn:SQLConnection = new SQLConnection();
// Create an instance of the File Class that points to the file
var db:File = File.applicationStorageDirectory.resolvePath("newDB.db");
// Open the connection - which will create the DB
conn.openAsync( db );
...
If you do not pass an instance of the File class to the open or openAsync methods, a database is created in memory, and it will remain as long as the application is open.
Affinity Types
Before you can create any tables, you will have to know about affinity types (data types) within SQLite. AIR contains ten different affinity types that can be used:
- TEXT (also called STRING)
- NUMERIC
- INTEGER:
- REAL (also called NUMBER)
- BOOLEAN
- DATE
- XML
- XMLLIST
- OBJECT
- NONE
NOTE: Each affinity can handle data differently. You will want to consult the information on Affinity Types in the documentation before you design your database schema.
Creating Tables
To create tables within AIR, you simply need to execute an SQLStatement just as you did to query the data. For example, let's say that you wanted to create a table names 'Contacts' with the following fields:
- firstName: This will just be a string
- lastName: This will just be a string
- age: This will be a uint
- gender: This will be a Boolean value
The table is created in the example below:
private function init():void {
dbFile = File.applicationDirectory.resolvePath( "contacts.db" );
conn = new SQLConnection();
conn.addEventListener(SQLEvent.OPEN, openSuccess);
conn.addEventListener(SQLErrorEvent.ERROR, openFailure);
conn.openAsync( dbFile );
}
private function openSuccess( event:SQLEvent ):void {
createTable();
}
private function openFailure( event:SQLEvent ):void {
throw new Error( 'Database Connection Failed' );
}
private function createTable():void {
var q:SQLStatement = new SQLStatement();
q.sqlConnection = conn;
var sql:String = "CREATE TABLE IF NOT EXISTS contacts( " +
"firstName TEXT, " +
"lastName TEXT, " +
"age INTEGER, " +
"gender BOOLEAN )";
q.text = sql;
q.addEventListener( SQLEvent.RESULT, queryResult );
q.addEventListener( SQLErrorEvent.ERROR, queryError );
q.execute();
}
private function queryError( event:SQLErrorEvent ):void {
trace( 'Create Table Failed' );
}
private function queryResult( event:SQLEvent ):void {
trace( 'Query Created Successfully' );
}
The actual SQL statement is found inside of the createTable method. There are a few things that could have been added to this table (such as an auto-incrementing ID field), but hopefully now you feel comfortable creating tables with the embedded SQLite database in AIR.
Deleting Tables
If you are in a situation where you need to delete a table, you will need to execute the following SQLStatement:
DROP TABLE IF EXISTS contacts;
If you omit the 'IF EXISTS' portion of the query, and the table does not exists (for example, if it was already deleted) the query response will be an error.





Facebook Application Development
Hey David, awesome series so far. Definitely beyond helpful in my quest to pick up AIR!! Is there any chance that you'll be covering the synchronization of the local SQLite DB with an external DB thats hosted on say a central server on the network as part of the series? I'd be very interested in that component. I can't seem to find too much of that discussed in depth elsewhere, just mentions of it here or there.
David,
I'm new to AIR development so maybe I'm not understanding correctly.
Following your example does the "contacts.db" only exist while the application is running? I can't find the database anywhere on my system even though I get the trace message "Query Created Successfully"?
Thank you
@Keith - it actually does exist as a file on your computer. The location is dependent on where your file reference was pointing to. For example, if you change the above code to be:
dbFile = File.desktopDirectory.resolvePath( "contacts.db" );
The file should show up on your desktop after running the application (and remain after the application is closed).
execuse me. I have a question which about use sqlconnection class to change encryption key. because i readed the document of Changing the encryption key of a database in Adobe AIR 1.5, and it prvoids "reencrypt" function to change encryption key, but i get the error message: Error #1069: Property reencrypt not found on flash.data.SQLConnection and there is no default value. When i use the reencrypt the function, the compiler doesn't show about any syntax error. so how do i slove the problem?
@Anonymous - What version of AIR are you targeting in your application descriptor file? You can find this in the root application node of the file. You need to be sure the XML namespace is declared for AIR 1.5 as you can see here: xmlns="http://ns.adobe.com/air/application/1.5".
David