SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
Introduction to SQLite
in Adobe AIR
Peter Elst - Flash Platform Consultant
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
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()
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;
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);
ïŹ‚ash.data.SQLConnection
■ Connects to the database ïŹle

■ Provides events for asynchronous use

■ Schema access
ïŹ‚ash.data.SQLStatement
■ Executes a SQL query on the speciïŹed database connection

■ Provides events for asynchronous use

■ Supports result paging
ïŹ‚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
Storage types
■ NULL - NULL value (null)

■ INTEGER - signed integer (int)

■ REAL - ïŹ‚oating point (Number)

■ TEXT - UTF16 text string (String)

■ BLOB - blob of data (ByteArray)
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
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;
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();
ïŹ‚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
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();
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
Schema demo
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);
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
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.
SQLite Tools
Mac OSX Terminal
Lita - SQLite database administration
DAO-Ext - value object generator
What is DAO?
■ Data Access Objects - abstract interface to a database
     ■ implements common features (select, update, delete, ...)
     ■ Uses value objects (VO)
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
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;
     }

     ...

 }
Example DAO
 public class contactsDAO {

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

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

 }
DAO demo
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()" />
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
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
SQLite wrapper demo
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
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

Weitere Àhnliche Inhalte

Was ist angesagt?

Ado.Net
Ado.NetAdo.Net
Ado.Net
LiquidHub
 
SQLite in Adobe AIR
SQLite in Adobe AIRSQLite in Adobe AIR
SQLite in Adobe AIR
Peter Elst
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
Madhuri Kavade
 

Was ist angesagt? (20)

JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScriptJavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
 
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
 
Oracle basic queries
Oracle basic queriesOracle basic queries
Oracle basic queries
 
Preethi apex-basics-jan19
Preethi apex-basics-jan19Preethi apex-basics-jan19
Preethi apex-basics-jan19
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Data Love Conference - Window Functions for Database Analytics
Data Love Conference - Window Functions for Database AnalyticsData Love Conference - Window Functions for Database Analytics
Data Love Conference - Window Functions for Database Analytics
 
Open Source World June '21 -- JSON Within a Relational Database
Open Source World June '21 -- JSON Within a Relational DatabaseOpen Source World June '21 -- JSON Within a Relational Database
Open Source World June '21 -- JSON Within a Relational Database
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
cPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven FeaturescPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven Features
 
Difference Between Sql - MySql and Oracle
Difference Between Sql - MySql and OracleDifference Between Sql - MySql and Oracle
Difference Between Sql - MySql and Oracle
 
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
 
Ado.Net
Ado.NetAdo.Net
Ado.Net
 
MYSQL
MYSQLMYSQL
MYSQL
 
Confoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & HistogramsConfoo 2021 - MySQL Indexes & Histograms
Confoo 2021 - MySQL Indexes & Histograms
 
Linq
LinqLinq
Linq
 
SQLite in Adobe AIR
SQLite in Adobe AIRSQLite in Adobe AIR
SQLite in Adobe AIR
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
How to execute an oracle stored procedure with nested table as a parameter fr...
How to execute an oracle stored procedure with nested table as a parameter fr...How to execute an oracle stored procedure with nested table as a parameter fr...
How to execute an oracle stored procedure with nested table as a parameter fr...
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and HistogramsDutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
 

Ähnlich wie Introduction to SQLite in Adobe AIR

Introduction to SQLite in Adobe AIR 1.5
Introduction to SQLite in Adobe AIR 1.5Introduction to SQLite in Adobe AIR 1.5
Introduction to SQLite in Adobe AIR 1.5
Peter Elst
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
Aren Zomorodian
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integration
webhostingguy
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
Madhuri Kavade
 

Ähnlich wie Introduction to SQLite in Adobe AIR (20)

Introduction to SQLite in Adobe AIR 1.5
Introduction to SQLite in Adobe AIR 1.5Introduction to SQLite in Adobe AIR 1.5
Introduction to SQLite in Adobe AIR 1.5
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Services
 
SQL for Web APIs - Simplifying Data Access for API Consumers
SQL for Web APIs - Simplifying Data Access for API ConsumersSQL for Web APIs - Simplifying Data Access for API Consumers
SQL for Web APIs - Simplifying Data Access for API Consumers
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
ASP.NET Lecture 4
ASP.NET Lecture 4ASP.NET Lecture 4
ASP.NET Lecture 4
 
ADO.NET by ASP.NET Development Company in india
ADO.NET by ASP.NET  Development Company in indiaADO.NET by ASP.NET  Development Company in india
ADO.NET by ASP.NET Development Company in india
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integration
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Jdbc
JdbcJdbc
Jdbc
 

Mehr von Peter Elst

P2P with Flash Player 10.1
P2P with Flash Player 10.1P2P with Flash Player 10.1
P2P with Flash Player 10.1
Peter Elst
 
Big boys and their litl toys
Big boys and their litl toysBig boys and their litl toys
Big boys and their litl toys
Peter Elst
 
FATC - AIR 2.0 workshop
FATC - AIR 2.0 workshopFATC - AIR 2.0 workshop
FATC - AIR 2.0 workshop
Peter Elst
 
Introduction to AS3Signals
Introduction to AS3SignalsIntroduction to AS3Signals
Introduction to AS3Signals
Peter Elst
 
The Secret Life of a Flash Freelancer
The Secret Life of a Flash FreelancerThe Secret Life of a Flash Freelancer
The Secret Life of a Flash Freelancer
Peter Elst
 
Getting Creative with Adobe AIR
Getting Creative with Adobe AIRGetting Creative with Adobe AIR
Getting Creative with Adobe AIR
Peter Elst
 
Creative Programming in ActionScript 3.0
Creative Programming in ActionScript 3.0Creative Programming in ActionScript 3.0
Creative Programming in ActionScript 3.0
Peter Elst
 
RIA meets Desktop
RIA meets DesktopRIA meets Desktop
RIA meets Desktop
Peter Elst
 
Object-Oriented ActionScript 3.0
Object-Oriented ActionScript 3.0Object-Oriented ActionScript 3.0
Object-Oriented ActionScript 3.0
Peter Elst
 
The Evolution of the Flash Platform
The Evolution of the Flash PlatformThe Evolution of the Flash Platform
The Evolution of the Flash Platform
Peter Elst
 

Mehr von Peter Elst (16)

P2P on the local network
P2P on the local networkP2P on the local network
P2P on the local network
 
P2P with Flash Player 10.1
P2P with Flash Player 10.1P2P with Flash Player 10.1
P2P with Flash Player 10.1
 
Big boys and their litl toys
Big boys and their litl toysBig boys and their litl toys
Big boys and their litl toys
 
Yes, you can do that with AIR 2.0
Yes, you can do that with AIR 2.0Yes, you can do that with AIR 2.0
Yes, you can do that with AIR 2.0
 
FATC - AIR 2.0 workshop
FATC - AIR 2.0 workshopFATC - AIR 2.0 workshop
FATC - AIR 2.0 workshop
 
Developing with Adobe AIR
Developing with Adobe AIRDeveloping with Adobe AIR
Developing with Adobe AIR
 
Introduction to AS3Signals
Introduction to AS3SignalsIntroduction to AS3Signals
Introduction to AS3Signals
 
The Secret Life of a Flash Freelancer
The Secret Life of a Flash FreelancerThe Secret Life of a Flash Freelancer
The Secret Life of a Flash Freelancer
 
Getting Creative with Adobe AIR
Getting Creative with Adobe AIRGetting Creative with Adobe AIR
Getting Creative with Adobe AIR
 
Creative Programming in ActionScript 3.0
Creative Programming in ActionScript 3.0Creative Programming in ActionScript 3.0
Creative Programming in ActionScript 3.0
 
RIA meets Desktop
RIA meets DesktopRIA meets Desktop
RIA meets Desktop
 
Object-Oriented ActionScript 3.0
Object-Oriented ActionScript 3.0Object-Oriented ActionScript 3.0
Object-Oriented ActionScript 3.0
 
The Evolution of the Flash Platform
The Evolution of the Flash PlatformThe Evolution of the Flash Platform
The Evolution of the Flash Platform
 
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIR
 
RIA meets Desktop
RIA meets DesktopRIA meets Desktop
RIA meets Desktop
 
SkillsMatter - In-the-Brain session - What's new in ActionScript 3.0
SkillsMatter - In-the-Brain session - What's new in ActionScript 3.0SkillsMatter - In-the-Brain session - What's new in ActionScript 3.0
SkillsMatter - In-the-Brain session - What's new in ActionScript 3.0
 

KĂŒrzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

KĂŒrzlich hochgeladen (20)

AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Introduction to SQLite in Adobe AIR

  • 1. Introduction to SQLite in Adobe AIR Peter Elst - Flash Platform Consultant
  • 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);
  • 6. ïŹ‚ash.data.SQLConnection ■ Connects to the database ïŹle ■ Provides events for asynchronous use ■ Schema access
  • 7. ïŹ‚ash.data.SQLStatement ■ Executes a SQL query on the speciïŹed database connection ■ Provides events for asynchronous use ■ Supports result paging
  • 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.
  • 22. Lita - SQLite database administration
  • 23. DAO-Ext - value object generator
  • 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