This document introduces SQLite database usage in Adobe AIR. It discusses how to create a connection to a SQLite database file, execute SQL statements, and work with the results both synchronously and asynchronously. It also covers database schema, parameters, transactions, encryption, and tools for working with SQLite in AIR.
2. Why SQLite in Adobe AIR?
â Embedded SQL Database Engine
â Implements most of SQL92
â Light-weight, cross-platform, open source
â No setup, conïŹguration or server required
â Each database is contained within a single ïŹle
3. How do you use it?
1. Create a File reference
2. Create an instance of ïŹash.data.SQLConnection and
ïŹash.data.SQLStatement
3. Open the database connection
4. Specify the connection and SQL query to run
5. Run SQLStatement.execute()
4. How do you use it?
import flash.filesystem.File;
import flash.data.*;
var dbFile:File =
File.applicationStorageDirectory.resolvePath("contacts.db");
var sqlConn:SQLConnection = new SQLConnection();
var sqlStatement:SQLStatement = new SQLStatement();
sqlConn.open(dbFile);
sqlStatement.sqlConnection = sqlConn;
sqlStatement.text = "SELECT * FROM contacts";
sqlStatement.execute();
var result:Array = sqlStatement.getResult().data;
5. Synchronous versus Asynchronous
â Synchronous - blocks application until result is available
var sqlConn:SQLConnection = new SQLConnection();
sqlConn.open(dbFile);
var result:SQLResult = sqlConn.getResult().result;
â Asynchronous - uses events and event listeners
var sqlConn:SQLConnection = new SQLConnection();
sqlConn.addEventListener(SQLResultEvent.RESULT, onSQLResult);
sqlConn.addEventListener(SQLResultEvent.ERROR, onSQLError);
sqlConn.openAsync(dbFile);
8. ïŹash.data.SQLMode
â SQLMode.CREATE (default)
â open connection and create database if it doesnât exist
â SQLMode.READ
â open connection as read only
â SQLMode.UPDATE
â open connection, donât create database if it doesnât exist
9. Storage types
â NULL - NULL value (null)
â INTEGER - signed integer (int)
â REAL - ïŹoating point (Number)
â TEXT - UTF16 text string (String)
â BLOB - blob of data (ByteArray)
10. AIR speciïŹc column afïŹnities
â String - String value (equivalent to TEXT)
â Number - ïŹoating point number (equivalent to REAL)
â Boolean - Boolean class
â Date - Date class
â XML - XML class
â XMLList - XMLList class
â Object - Object class
11. SQLStatement Parameters
â The parameters feature protects your SQL statements from
SQL injection
var sqlStatement:SQLStatement = new SQLStatement();
sqlStatement.sqlConnection = sqlConn;
sqlStatement.text = "SELECT * FROM contacts WHERE id = @ID";
sqlStatement.parameters["@ID"] = someVariable;
sqlStatement.execute();
â You can use the @ or : symbol to denote a parameter to be
replaced, works both string based as index based
sqlStatement.parameters[0] = someVariable;
12. Result Paging
â Paging allows you to limit the amount of rows you get
returned when doing a select operation
var sqlStatement:SQLStatement = new SQLStatement();
sqlStatement.sqlConnection = sqlConn;
sqlStatement.text = "SELECT * FROM contacts";
sqlStatement.execute(10);
â You can get the next batch of rows returned by calling the
next method on the SQLStatement instance
sqlStatement.next();
13. ïŹash.data.SQLResult
â SQLResult.data - array of objects for each row of the result
â SQLResult.complete - returns a boolean indicating whether
or not the full result was shown
â SQLResult.lastInsertRowID - return id for the last row that
was inserted
â SQLResult.rowsAffected - number of rows affected by an
insert, update or delete operation
14. Transactions
â Transactions allow multiple SQL statements to run within one
write operation to the database
â Much more optimized way of handling large insert operations,
allows rollback of the complete transaction if an error occurs
var sqlStatement:SQLStatement = new SQLStatement();
sqlStatement.sqlConnection = sqlConn;
sqlStatement.text = "INSERT into contacts VALUES (@NAME, @EMAIL)";
sqlConn.begin();
for(var i:uint=0; i<contacts.length; i++) {
sqlStatement.parameters["@NAME"] = contacts[i].name;
sqlStatement.parameters["@EMAIL"] = contacts[i].email;
sqlStatement.execute();
}
sqlConn.commit();
15. Database Schema
â Allows you to introspect tables, views, columns, indices, triggers
var sqlConn:SQLConnection = new SQLConnection();
sqlConn.open(dbFile);
sqlConn.loadSchema();
var result:SQLSchemaResult = sqlConn.getSchemaResult();
var table:SQLTableSchema = result.tables[0];
var column:SQLColumnSchema = table.columns[0];
trace(column.name);
// returns name of the first column in the first table
17. Database encryption
â New feature in AIR 1.5
â Password protect database ïŹles
var encryptionKey:ByteArray = new ByteArray();
encryptionKey.writeUTFBytes("notverysecretpassword");
var sqlConn:SQLConnection = new SQLConnection();
sqlConn.open(dbFile,SQLMode.READ,null,false,1024,encryptionKey);
18. Encryption best practices
â Do not embed passwords in your application!
â com.adobe.air.crypto.EncryptionKeyGenerator
â Secure solution: creates random salt and stores in the
EncryptedLocalStore (linked to user and machine)
â Prevents dictionary attack
â com.dehats.air.sqlite.SimpleEncryptionKeyGenerator
â Less secure but allows access by other users and other
applications, doesnât generate a random salt value.
http://bit.ly/SimpleEncryptionKeyGenerator
19. Database synchronization
â Synchronize database between server and client(s)
â Some different strategies
â overwrite (server overwrites client)
â check what to synchronize
â timestamp ïŹeld
â ïŹeld by ïŹeld comparison
â dirty ïŹag
â LiveCycle Data Services has built-in SQLite synchronization
support including ofïŹine caching and conïŹict management.
24. What is DAO?
â Data Access Objects - abstract interface to a database
â implements common features (select, update, delete, ...)
â Uses value objects (VO)
25. What is DAO?
â Data Access Objects - abstract interface to a database
â implements common features (select, update, delete, ...)
â Uses value objects (VO)
â Value Objects (also known as Data Transfer Objects)
â donât implement any behavior
â encapsulates properties through getter/setter methods
â represent an entry in a database table
26. Example VO
public class contactsVO {
private var _name:String;
public function get name():String {
return _name;
}
public function set name(value:String):void {
_name = value;
}
...
}
27. Example DAO
public class contactsDAO {
public function insertRow(rowItem:contactsVO):void {
...
}
public function updateRow(rowItem:contactsVO):void {
...
}
public function deleteRow(rowItem:contactsVO):void {
...
}
}
29. SQLite wrapper classes
â Simple way to use SQLite features in your application
â ActionScript 3.0 classes, primarily for use as tags in MXML
<sql:SQLite id="myDB" file="contacts.db" open="myQuery.execute()" />
<sql:Query id="myQuery" connection="{myDB.connection}"
sql="SELECT * FROM contacts" />
<mx:DataGrid id="myDataGrid" dataProvider="{myQuery.data}" />
<mx:Button label="Refresh data" click="myQuery.execute()" />
30. SQLite wrapper - SQLite class
â Properties
â ïŹle - name of database ïŹle
â connection - returns SQLConnection instance
â Methods
â open - create database connection
â close - close database connection
â Events
â open - database connection is opened
â close - database connection is closed
â error - error connecting to database
31. SQLite wrapper - Query class
â Properties
â connection - reference to SQLConnection
â sql - String value of SQL statement
â parameters - parameters for SQL statement
â data - result returned from query
â Methods
â execute - run query on database
â Events
â result - result received from query
â error - error executing query
33. Resources
â Lita - SQLite Administration Tool by David Deraedt
www.dehats.com/drupal/?q=node/58
â DAO-Ext by Comtaste
code.google.com/p/dao-ext/
â Adobe AIR Developer Center
www.adobe.com/devnet/air/
â Adobe AIR Marketplace
www.adobe.com/go/airmarketplace
34. Thanks for your time
Any questions or feedback - feel free to get in touch!
blog www.peterelst.com
email info@peterelst.com
twitter @peterelst
e confe rence!
rest o f th
En joy the