introduction to sqlite in adobe air

34
Introduction to SQLite in Adobe AIR Peter Elst - Flash Platform Consultant

Upload: peter-elst

Post on 18-Dec-2014

16.335 views

Category:

Technology


2 download

DESCRIPTION

updated presentation on using local SQLite database support in Adobe AIR 1.5 for Flash at the Lake in Zurich - Switzerland (June 26th 2009)

TRANSCRIPT

Page 1: Introduction to SQLite in Adobe AIR

Introduction to SQLitein Adobe AIRPeter Elst - Flash Platform Consultant

Page 2: Introduction to SQLite in Adobe AIR

■ Embedded SQL Database Engine

■ Implements most of SQL92

■ Light-weight, cross-platform, open source

■ No setup, configuration or server required

■ Each database is contained within a single file

Why SQLite in Adobe AIR?

Page 3: Introduction to SQLite in Adobe AIR

1. Create a File reference

2. Create an instance of flash.data.SQLConnection and flash.data.SQLStatement

3. Open the database connection

4. Specify the connection and SQL query to run

5. Run SQLStatement.execute()

How do you use it?

Page 4: Introduction to SQLite in Adobe AIR

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;

How do you use it?

Page 5: Introduction to SQLite in Adobe AIR

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);

Page 6: Introduction to SQLite in Adobe AIR

■ Connects to the database file

■ Provides events for asynchronous use

■ Schema access

flash.data.SQLConnection

Page 7: Introduction to SQLite in Adobe AIR

■ Executes a SQL query on the specified database connection

■ Provides events for asynchronous use

■ Supports result paging

flash.data.SQLStatement

Page 8: Introduction to SQLite in Adobe AIR

■ 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

flash.data.SQLMode

Page 9: Introduction to SQLite in Adobe AIR

■ NULL - NULL value (null)

■ INTEGER - signed integer (int)

■ REAL - floating point (Number)

■ TEXT - UTF16 text string (String)

■ BLOB - blob of data (ByteArray)

Storage types

Page 10: Introduction to SQLite in Adobe AIR

■ String - String value (equivalent to TEXT)

■ Number - floating point number (equivalent to REAL)

■ Boolean - Boolean class

■ Date - Date class

■ XML - XML class

■ XMLList - XMLList class

■ Object - Object class

AIR specific column affinities

Page 11: Introduction to SQLite in Adobe AIR

■ 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;

SQLStatement Parameters

Page 12: Introduction to SQLite in Adobe AIR

■ 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();

Result Paging

Page 13: Introduction to SQLite in Adobe AIR

■ 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

flash.data.SQLResult

Page 14: Introduction to SQLite in Adobe AIR

■ 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();

Transactions

Page 15: Introduction to SQLite in Adobe AIR

■ 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

Database Schema

Page 16: Introduction to SQLite in Adobe AIR

Schema demo

Page 17: Introduction to SQLite in Adobe AIR

■ New feature in AIR 1.5

■ Password protect database files

var encryptionKey:ByteArray = new ByteArray(); encryptionKey.writeUTFBytes("notverysecretpassword");

var sqlConn:SQLConnection = new SQLConnection(); sqlConn.open(dbFile,SQLMode.READ,null,false,1024,encryptionKey);

Database encryption

Page 18: Introduction to SQLite in Adobe AIR

■ 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

Encryption best practices

Page 19: Introduction to SQLite in Adobe AIR

■ Synchronize database between server and client(s)

■ Some different strategies

■ overwrite (server overwrites client)

■ check what to synchronize

■ timestamp field

■ field by field comparison

■ dirty flag

■ LiveCycle Data Services has built-in SQLite synchronization support including offline caching and conflict management.

Database synchronization

Page 20: Introduction to SQLite in Adobe AIR

SQLite Tools

Page 21: Introduction to SQLite in Adobe AIR

Mac OSX Terminal

Page 22: Introduction to SQLite in Adobe AIR

Lita - SQLite database administration

Page 23: Introduction to SQLite in Adobe AIR

DAO-Ext - value object generator

Page 24: Introduction to SQLite in Adobe AIR

■ Data Access Objects - abstract interface to a database

■ implements common features (select, update, delete, ...)

■ Uses value objects (VO)

What is DAO?

Page 25: Introduction to SQLite in Adobe AIR

■ 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

What is DAO?

Page 26: Introduction to SQLite in Adobe AIR

public class contactsVO {

private var _name:String;

public function get name():String {

return _name;

}

public function set name(value:String):void {

_name = value;

}

...

}

Example VO

Page 27: Introduction to SQLite in Adobe AIR

public class contactsDAO {

public function insertRow(rowItem:contactsVO):void {

...

}

public function updateRow(rowItem:contactsVO):void {

...

}

public function deleteRow(rowItem:contactsVO):void { ... }

}

Example DAO

Page 28: Introduction to SQLite in Adobe AIR

DAO demo

Page 29: Introduction to SQLite in Adobe AIR

■ 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()" />

SQLite wrapper classes

Page 30: Introduction to SQLite in Adobe AIR

■ Properties

■ file - name of database file

■ 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

SQLite wrapper - SQLite class

Page 31: Introduction to SQLite in Adobe AIR

■ 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

SQLite wrapper - Query class

Page 32: Introduction to SQLite in Adobe AIR

SQLite wrapper demo

Page 33: Introduction to SQLite in Adobe AIR

■ Lita - SQLite Administration Tool by David Deraedtwww.dehats.com/drupal/?q=node/58

■ DAO-Ext by Comtastecode.google.com/p/dao-ext/

■ Adobe AIR Developer Centerwww.adobe.com/devnet/air/

■ Adobe AIR Marketplacewww.adobe.com/go/airmarketplace

Resources

Page 34: Introduction to SQLite in Adobe AIR

Any questions or feedback - feel free to get in touch!

Thanks for your time

Enjoy the rest of the conference!

blog www.peterelst.com

email [email protected]

twitter @peterelst