SlideShare une entreprise Scribd logo
1  sur  37
Télécharger pour lire hors ligne
Android & PostgreSQL

       Mark Wong
  markwkm@postgresql.org
   PGCon 2011, University of Ottawa


         20 May 2011
__      __
          / ~~~/  . o O ( Hello! )
    ,----(       oo     )
  /        __      __/
 /|            ( |(
^     /___ / |
    |__|    |__|-"


Slides available at http://www.sideshare.net/markwkm



  markwkm (PGCon2011)        Android & PostgreSQL      20 May 2011   2 / 37
Overview



  Two topics, mostly the latter:
   • Development environment specific for PostgreSQL JDBC
   • Code samples for using the PostgreSQL JDBC driver

  Any requests?




    markwkm (PGCon2011)        Android & PostgreSQL        20 May 2011   3 / 37
Audience Survey


  Are you familiar with:
    • Developed an Android application?
    • Java?
    • JDBC?
    • Eclipse?
    • SQL?
    • PostgreSQL?




    markwkm (PGCon2011)          Android & PostgreSQL   20 May 2011   4 / 37
Development Environment


  A few details on the following slides about:
    • JDK5 or JDK6
    • Android SDK
    • PostgreSQL JDBC Driver
    • Eclipse is optional, current Android SDK r11 requires 3.5 or 3.6

  Full system requirement details for Android development:
  http://developer.android.com/sdk/requirements.html



    markwkm (PGCon2011)            Android & PostgreSQL                  20 May 2011   5 / 37
PostgreSQL JDBC Driver
  http://jdbc.postgresql.org/
    • Distributed under BSD License.
      (http://jdbc.postgresql.org/license.html)
    • Supports PostgreSQL 7.2 and laster version
    • Thread-safe
      (http://jdbc.postgresql.org/documentation/head/thread.html)
    • JDBC3 vs. JDBC4 (http://jdbc.postgresql.org/download.html)
      • If you are using the 1.6 JVM, then you should use the JDBC4 version.
      • JDK 1.4, 1.5 - JDBC 3. This contains support for SSL and javax.sql, but does not
        require J2EE as it has been added to the J2SE release.
      • JDK 1.6 - JDBC4. Support for JDBC4 methods is limited. The driver builds, but
        the several of the new methods are stubbed out.
   • Todo list http://jdbc.postgresql.org/todo.html
    markwkm (PGCon2011)               Android & PostgreSQL                     20 May 2011   6 / 37
Using the PostgreSQL JDBC Driver

  To add the PostgreSQL JDBC driver for building and packaging edit the
  hidden .classpath file at the top level of the project directory with the full
  path to the JAR file:
  < c l a s s p a t h>
      ...
     < c l a s s p a t h e n t r y k i n d=” l i b ”
              p a t h=”/ w o r k s p a c e / p r o j / p o s t g r e s q l −9.0 −801. j d b c 4 . j a r ”/>
      ...
  </ c l a s s p a t h>

  Alternate instructions when using Eclipse:
  http://developer.android.com/resources/faq/commontasks.html#addexternallibrary


      markwkm (PGCon2011)                         Android & PostgreSQL                                 20 May 2011   7 / 37
PostgreSQL JDBC Version Notes



  Dave Cramer built a special version of the PostgreSQL JDBC driver that
  works on Android 1.5 and later and posted it in a discussion in the PgAndroid
  Google Group (this pdf should be built so you can click on the tiny text to
  open the link):
  http://groups.google.com/group/pgandroid/browse_thread/thread/d8b400f039f66d5f/f77b2e2a99370a36?lnk=raot#f77b2e2a99370a36



  At this time, build 801 of the JDBC driver works with Android 2.1 and later.




      markwkm (PGCon2011)                             Android & PostgreSQL                                       20 May 2011   8 / 37
PostgreSQL JDBC Code Examples



    • Some simple examples for connecting to a PostgreSQL database and
      querying some data, and PostgreSQL specific features
    • Most examples are variations of those given in the PostgreSQL and
      PostgreSQL JDBC documentation

  Warning: code formatted to fit better on these slides. . .




    markwkm (PGCon2011)            Android & PostgreSQL              20 May 2011   9 / 37
Open a Database Connection

  Load the PostgreSQL JDBC driver and open a database connection using SSL:
  C l a s s . forName ( ” o r g . p o s t g r e s q l . D r i v e r ” ) ;
  String url ;
  u r l = ” jdbc : p o s t g r e s q l :// pghost :5432/ pgdatabase ” +
              ” ? s s l f a c t o r y =o r g . p o s t g r e s q l . s s l . N o n V a l i d a t i n g F a c t o r y ” +
              ”& s s l =t r u e ” ;
  C o n n e c t i o n conn = D r i v e r M a n a g e r . g e t C o n n e c t i o n ( u r l ,
                                                                                            ” pguser ” ,
                                                                                            ” pgpass ” ) ;
  // Don ’ t f o r g e t t o c l o s e t h e c o n n e c t i o n when you ’ r e done .
  // conn . c l o s e ( ) ;



      markwkm (PGCon2011)                             Android & PostgreSQL                                     20 May 2011   10 / 37
Execute a Query

  Select the name of all relations from pg class and iterate through every row
  returned:
  String sql ;
  s q l = ”SELECT r e l n a m e FROM p g c l a s s WHERE r e l k i n d = ’ r ’ ; ”

  S t a t e m e n t s t = conn . c r e a t e S t a t e m e n t ( ) ;
  ResultSet r s = st . executeQuery ( s q l ) ;
  while ( r s . next ( ) ) {
          // Columns a r e can be r e f e r e n c e d by name .
           S t r i n g relname = r s . g e t S t r i n g ( ” relname ” ) ;
  }
  rs . close ();
  st . close ();


     markwkm (PGCon2011)                     Android & PostgreSQL                20 May 2011   11 / 37
Execute a Query Using a Cursor
  Select the name of all table names from pg tables and iterate through them
  fetching 10 at a time:
  conn . setAutoCommit ( f a l s e ) ;
  S t r i n g s q l = ”SELECT t a b l e n a m e FROM p g t a b l e s ; ”

  S t a t e m e n t s t = conn . c r e a t e S t a t e m e n t ( ) ;
  st . setFetchSize (10);
  ResultSet r s = st . executeQuery ( s q l ) ;
  while ( r s . next ( ) ) {
          // Columns a r e can be r e f e r e n c e d by name .
           S t r i n g relname = r s . g e t S t r i n g ( ” relname ” ) ;
  }
  rs . close ();
  st . close ();

     markwkm (PGCon2011)                     Android & PostgreSQL            20 May 2011   12 / 37
Execute a Query with a Bind Value
  Building on the previous slide, select the number of all relations from pg class:
  S t r i n g s q l = ”SELECT COUNT( ∗ ) FROM p g c l a s s WHERE r e l k i n d = ? ; ”

  P r e p a r e d S t a t e m e n t ps = conn . c r e a t e S t a t e m e n t ( ) ;
  // Bind v a r i a b l e s a r e e n u m e r a t e d s t a r t i n g w i t h 1 ;
  ps . s e t S t r i n g ( 1 , ” r ” ) ;
  R e s u l t S e t r s = ps . e x e c u t e Q u e r y ( s q l ) ;

  rs . next ( ) ;
   Columns a r e e n u m e r a t e d s t a r t i n g w i t h 1 .
  long c o u n t = r s . g e t L o n g ( 1 ) ;

  rs . close ();
  ps . c l o s e ( ) ;

     markwkm (PGCon2011)                      Android & PostgreSQL                    20 May 2011   13 / 37
Some addition methods for retrieving column data



              getBoolean ()                          getLong ( )
              getDate ()                             getShort ()
              getDouble ()                           getString ()
              getFloat ()                            getTime ( )
              getInt ()                              getTimestamp ( )




    markwkm (PGCon2011)       Android & PostgreSQL                      20 May 2011   14 / 37
Create, Modify, or Drop Database Objects



  Execute CREATE, ALTER, or DROP SQL statements with the execute() method:
  S t a t e m e n t s t = conn . c r e a t e S t a t e m e n t ( ) ;
  s t . e x e c u t e ( ”CREATE TABLE f i l m s ( t i t l e VARCHAR ( 4 0 ) ; ” ) ;
  st . close ();




    markwkm (PGCon2011)              Android & PostgreSQL                  20 May 2011   15 / 37
Example for INSERT, UPDATE and DELETE

  Executing INSERT, UPDATE, or DELETE SQL statements use the
  executeUpdate() as opposed to the executeQuery() method shown previously
  with SELECT statements. Also, executeUpdate() returns the number of rows
  affected as opposed to a ResultSet, otherwise usage is mostly the same:
  PreparedStatement st =
                  conn . p r e p a r e S t a t e m e n t (
                                ”INSERT INTO f i l m s ( t i t l e ) ” +
                                ”VALUES ( ? ) ; ” ) ;
  s t . s e t S t r i n g ( 1 , ”On S t r a n g e r T i d e s ” ) ;
  i n t rows = s t . e x e c u t e U p d a t e ( ) ;
  st . close ();

    markwkm (PGCon2011)             Android & PostgreSQL                   20 May 2011   16 / 37
Example for Calling Stored Functions

  Call a built-in stored function that returns a value. In this example, call
  upper() to change a string to all upper case characters:
  CallableStatement upperProc =
                  conn . p r e p a r e C a l l ( ”{ ? = c a l l u p p e r ( ? ) }” ) ;
  u p p e r P r o c . r e g i s t e r O u t P a r a m e t e r ( 1 , Types . VARCHAR ) ;
  upperProc . s e t S t r i n g (2 , ” lowercase to uppercase ” ) ;
  upperProc . execute ( ) ;
  S t r i n g upperCased = upperProc . g e t S t r i n g ( 1 ) ;
  upperProc . c l o s e ( ) ;



    markwkm (PGCon2011)                Android & PostgreSQL                      20 May 2011   17 / 37
LISTEN & NOTIFY & UNLISTEN




  http://jdbc.postgresql.org/documentation/head/listennotify.html




    markwkm (PGCon2011)         Android & PostgreSQL                20 May 2011   18 / 37
Starting listening to a channel



  Register this session as a listener to the notification channel virtual:
   S t a t e m e n t stmt = conn . c r e a t e S t a t e m e n t ( ) ;
   stmt . e x e c u t e ( ”LISTEN v i r t u a l ; ” ) ;
   stmt . c l o s e ( ) ;




     markwkm (PGCon2011)                 Android & PostgreSQL               20 May 2011   19 / 37
LISTEN: Dummy query

  Need to issue a dummy query to contact the PostgreSQL database before any
  pending notifications are received:
  while ( true ) {
      try {
           S t a t e m e n t stmt = conn . c r e a t e S t a t e m e n t ( ) ;
           R e s u l t S e t r s = stmt . e x e c u t e Q u e r y ( ”SELECT 1 ; ” ) ;
           rs . close ();
           stmt . c l o s e ( ) ;
  ...



    markwkm (PGCon2011)              Android & PostgreSQL                   20 May 2011   20 / 37
LISTEN: Handle notifications
        A key limitation of the JDBC driver is that it cannot receive
        asynchronous notifications and must poll the backend to check if any
        notifications were issued.
  ...
              org . p o s t g r e s q l . PGNotification n o t i f i c a t i o n s [ ] =
                           pgconn . g e t N o t i f i c a t i o n s ( ) ;
              i f ( n o t i f i c a t i o n s != n u l l ) {
                    f o r ( i n t i =0; i < n o t i f i c a t i o n s . l e n g t h ; i ++) {
                           // Handle h e r e : n o t i f i c a t i o n s [ i ] . getName ( ) ) ;
                    }
              }

              // Wait b e f o r e c h e c k i n g f o r more n o t i f i c a t i o n s .
              Thread . s l e e p ( 5 0 0 ) ;
  ...
    markwkm (PGCon2011)                     Android & PostgreSQL                           20 May 2011   21 / 37
LISTEN: Java Exception Handling


  ...
          } catch ( SQLException s q l e ) {
              sqle . printStackTrace ();
          } catch ( I n t e r r u p t e d E x c e p t i o n i e ) {
              ie . printStackTrace ();
          }
  }




      markwkm (PGCon2011)               Android & PostgreSQL          20 May 2011   22 / 37
Stop listening to a channel



  Stop listening to the channel virtual:
   S t a t e m e n t stmt = conn . c r e a t e S t a t e m e n t ( ) ;
   stmt . e x e c u t e ( ”UNLISTEN v i r t u a l ; ” ) ;
   stmt . c l o s e ( ) ;




     markwkm (PGCon2011)                 Android & PostgreSQL            20 May 2011   23 / 37
NOTIFY: Send a notification


  Send a notification to the channel virtual:
  S t a t e m e n t stmt = conn . c r e a t e S t a t e m e n t ( ) ;
  stmt . e x e c u t e ( ”NOTIFY v i r t u a l ; ” ) ;
  stmt . c l o s e ( ) ;

  Note: Starting with PostgreSQL 9.0, there is the stored function
  pg notify(text, text) that can be used.




    markwkm (PGCon2011)                 Android & PostgreSQL            20 May 2011   24 / 37
Server Prepared Statements

  JDBC allows a threshold to be set before the server prepared statement is
  used. Recommended to use with PostgreSQL 7.4 and later:
  http://jdbc.postgresql.org/documentation/81/server-prepare.html
  P r e p a r e d S t a t e m e n t pstmt = conn . p r e p a r e S t a t e m e n t ( ”SELECT ? ; ” ) ;
  // C a s t t h e P r e p a r e d S t a t e m e n t t o t h e PostgreSQL s p e c i f i c
  // PGStatement .
  o r g . p o s t g r e s q l . PGStatement pgstmt =
                  ( o r g . p o s t g r e s q l . PGStatement ) pstmt ;
  // Use p r e p a r e d s t a t e m e n t on t h e 2 nd e x e c u t i o n onward .
  pgstmt . s e t P r e p a r e T h r e s h o l d ( 2 ) ;
  pstmt . s e t I n t ( 1 , 4 2 ) ;
  R e s u l t S e t r s = pstmt . e x e c u t e Q u e r y ( ) ;
  pstmt . c l o s e ( ) ;


     markwkm (PGCon2011)                      Android & PostgreSQL                             20 May 2011   25 / 37
Geometric data types



  PostgreSQL data types that include single points, lines, and polygons:
  http://jdbc.postgresql.org/documentation/81/geometric.html

  Circle example:
  stmt . e x e c u t e ( ”CREATE TABLE geo ( m y c i r c c i r c l e ) ; ” ) ;




    markwkm (PGCon2011)              Android & PostgreSQL                    20 May 2011   26 / 37
INSERT a circle


  PGpoint c e n t e r = new PGpoint ( 1 , 2 . 5 ) ;
  double r a d i u s = 4 ;
  P G c i r c l e c i r c l e = new P G c i r c l e ( c e n t e r , r a d i u s ) ;
  P r e p a r e d S t a t e m e n t ps = conn . p r e p a r e S t a t e m e n t (
                  ”INSERT INTO g e o m t e s t ( m y c i r c ) VALUES ( ? ) ; ” ) ;
  ps . s e t O b j e c t ( 1 , c i r c l e ) ;
  ps . e x e c u t e U p d a t e ( ) ;




    markwkm (PGCon2011)              Android & PostgreSQL                    20 May 2011   27 / 37
SELECT a circle



  R e s u l t S e t r s = stmt . e x e c u t e Q u e r y (
         ”SELECT m y c i r c FROM geo ; ” ) ;
  rs . next ( ) ;
  PGcircle c i r c l e = ( PGcircle ) rs . getObject (1);
  PGpoint c e n t e r = c i r c l e . c e n t e r ;
  double r a d i u s = c i r c l e . r a d i u s ;




    markwkm (PGCon2011)       Android & PostgreSQL           20 May 2011   28 / 37
JDBC Escapes
  A special escape syntax that is JDBC specific and database agnostic:
  http://jdbc.postgresql.org/documentation/head/escapes.html

  Dates and timestamps:
  s t . e x e c u t e Q u e r y ( ”SELECT { f n week ({ d ’2005 −01 −24 ’})}; ” ) ;
  st . executeQuery (
          ”SELECT { f n week ({ t s ’2005−01−24 1 2 : 1 3 : 1 4 . 1 5 ’ } ) } ; ” ) ;
  Joins:
  st . executeQuery (
        ”SELECT ∗ FROM { o j a LEFT OUTER JOIN b ON ( a . i = b . i ) } ; ” ) ;

  Scalar functions:
  s t . e x e c u t e Q u e r y ( ”SELECT { f n a b s ( −1)}; ” ) ;
    markwkm (PGCon2011)                Android & PostgreSQL              20 May 2011   29 / 37
Handling binary data




  Long examples for using the bytea data type and Large Objects:
  http://jdbc.postgresql.org/documentation/head/binary-data.html




    markwkm (PGCon2011)     Android & PostgreSQL        20 May 2011   30 / 37
Connection pools




  Long examples for using JDBC connection pooling:
  http://jdbc.postgresql.org/documentation/head/datasource.html




    markwkm (PGCon2011)     Android & PostgreSQL        20 May 2011   31 / 37
Example application



  PGTop for Android is a complete application implementing some of the
  examples shown here:
    • Source code: https://github.com/markwkm/pgtop
    • Android Market:
      https://market.android.com/details?id=org.postgresql.top




    markwkm (PGCon2011)         Android & PostgreSQL             20 May 2011   32 / 37
Android Example Programs


  For reference, since not covered in this presentation:
    • Hello, World (includes example without using Eclipse)
      http://developer.android.com/resources/tutorials/hello-world.html
    • More examples without using Eclipse http:
      //developer.android.com/guide/developing/other-ide.html
    • Even more sample applications
      http://developer.android.com/resources/samples/




    markwkm (PGCon2011)           Android & PostgreSQL            20 May 2011   33 / 37
Further JDBC Reading




  JDBC API Documentation and JDBC Specification
  http://jdbc.postgresql.org/documentation/head/reading.html




    markwkm (PGCon2011)     Android & PostgreSQL        20 May 2011   34 / 37
__      __
          / ~~~/  . o O ( Thank you! )
    ,----(       oo     )
  /        __      __/
 /|            ( |(
^     /___ / |
    |__|    |__|-"




  markwkm (PGCon2011)    Android & PostgreSQL   20 May 2011   35 / 37
Acknowledgements

  Hayley Jane Wakenshaw

              __      __
            / ~~~/ 
      ,----(       oo     )
    /        __      __/
   /|            ( |(
  ^     /___ / |
      |__|    |__|-"




    markwkm (PGCon2011)       Android & PostgreSQL   20 May 2011   36 / 37
License



  This work is licensed under a Creative Commons Attribution 3.0 Unported
  License. To view a copy of this license, (a) visit
  http://creativecommons.org/licenses/by/3.0/us/; or, (b) send a
  letter to Creative Commons, 171 2nd Street, Suite 300, San Francisco,
  California, 94105, USA.




    markwkm (PGCon2011)          Android & PostgreSQL               20 May 2011   37 / 37

Contenu connexe

Tendances

GDI - Intro to WordPress
GDI - Intro to WordPressGDI - Intro to WordPress
GDI - Intro to WordPress
Suzette Franck
 
Adobe Photoshop Toolbox definition term
Adobe Photoshop Toolbox definition termAdobe Photoshop Toolbox definition term
Adobe Photoshop Toolbox definition term
Allan Roloma
 

Tendances (20)

introduction to blender
introduction to blenderintroduction to blender
introduction to blender
 
Designing with Canva
Designing with CanvaDesigning with Canva
Designing with Canva
 
canva presentation
canva presentationcanva presentation
canva presentation
 
Introduction To WordPress
Introduction To WordPressIntroduction To WordPress
Introduction To WordPress
 
Wordpress ppt
Wordpress pptWordpress ppt
Wordpress ppt
 
423480261-Filmora-Presentation.pptx
423480261-Filmora-Presentation.pptx423480261-Filmora-Presentation.pptx
423480261-Filmora-Presentation.pptx
 
Canva Turorial
Canva TurorialCanva Turorial
Canva Turorial
 
Canva 101 Presentation by Gael Gilliland
Canva 101 Presentation by Gael GillilandCanva 101 Presentation by Gael Gilliland
Canva 101 Presentation by Gael Gilliland
 
How to use canva
How to use canva How to use canva
How to use canva
 
Recommender Systems
Recommender SystemsRecommender Systems
Recommender Systems
 
How to use Canva
How to use CanvaHow to use Canva
How to use Canva
 
Search engine
Search engineSearch engine
Search engine
 
Intro to Wordpress
Intro to WordpressIntro to Wordpress
Intro to Wordpress
 
Use of data science in recommendation system
Use of data science in  recommendation systemUse of data science in  recommendation system
Use of data science in recommendation system
 
GDI - Intro to WordPress
GDI - Intro to WordPressGDI - Intro to WordPress
GDI - Intro to WordPress
 
Basic Wordpress PPT
Basic Wordpress PPT Basic Wordpress PPT
Basic Wordpress PPT
 
Adobe Photoshop Toolbox definition term
Adobe Photoshop Toolbox definition termAdobe Photoshop Toolbox definition term
Adobe Photoshop Toolbox definition term
 
Responsive web designing ppt(1)
Responsive web designing ppt(1)Responsive web designing ppt(1)
Responsive web designing ppt(1)
 
Photoshop Introduction
Photoshop IntroductionPhotoshop Introduction
Photoshop Introduction
 
What Is PowerPoint?
What Is PowerPoint?What Is PowerPoint?
What Is PowerPoint?
 

En vedette

Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Nikolay Samokhvalov
 
Blind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization TechniquesBlind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization Techniques
guest54de52
 
PostgreSQL Performance Tuning
PostgreSQL Performance TuningPostgreSQL Performance Tuning
PostgreSQL Performance Tuning
elliando dias
 

En vedette (20)

PGTop for Android: Things I learned making this app
PGTop for Android: Things I learned making this appPGTop for Android: Things I learned making this app
PGTop for Android: Things I learned making this app
 
Reactive programming with rx java
Reactive programming with rx javaReactive programming with rx java
Reactive programming with rx java
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
 
Pro PostgreSQL, OSCon 2008
Pro PostgreSQL, OSCon 2008Pro PostgreSQL, OSCon 2008
Pro PostgreSQL, OSCon 2008
 
Building a Spatial Database in PostgreSQL
Building a Spatial Database in PostgreSQLBuilding a Spatial Database in PostgreSQL
Building a Spatial Database in PostgreSQL
 
Stored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlStored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sql
 
Query Optimization in SQL Server
Query Optimization in SQL ServerQuery Optimization in SQL Server
Query Optimization in SQL Server
 
안드로이드 DB, 서버 연동하기
안드로이드 DB, 서버 연동하기안드로이드 DB, 서버 연동하기
안드로이드 DB, 서버 연동하기
 
PostgreSQL Scaling And Failover
PostgreSQL Scaling And FailoverPostgreSQL Scaling And Failover
PostgreSQL Scaling And Failover
 
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
 
My experience with embedding PostgreSQL
 My experience with embedding PostgreSQL My experience with embedding PostgreSQL
My experience with embedding PostgreSQL
 
Federal mobile 2015
Federal mobile 2015Federal mobile 2015
Federal mobile 2015
 
My sql optimization
My sql optimizationMy sql optimization
My sql optimization
 
Why use PostgreSQL?
Why use PostgreSQL?Why use PostgreSQL?
Why use PostgreSQL?
 
PostgreSQL Hooks for Fun and Profit
PostgreSQL Hooks for Fun and ProfitPostgreSQL Hooks for Fun and Profit
PostgreSQL Hooks for Fun and Profit
 
Blind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization TechniquesBlind SQL Injection - Optimization Techniques
Blind SQL Injection - Optimization Techniques
 
PostgreSQL and RAM usage
PostgreSQL and RAM usagePostgreSQL and RAM usage
PostgreSQL and RAM usage
 
Потоковая репликация PostgreSQL
Потоковая репликация PostgreSQLПотоковая репликация PostgreSQL
Потоковая репликация PostgreSQL
 
Get to know PostgreSQL!
Get to know PostgreSQL!Get to know PostgreSQL!
Get to know PostgreSQL!
 
PostgreSQL Performance Tuning
PostgreSQL Performance TuningPostgreSQL Performance Tuning
PostgreSQL Performance Tuning
 

Similaire à Android & PostgreSQL

Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
phanleson
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
leminhvuong
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
phanleson
 
11 Things About 11gr2
11 Things About 11gr211 Things About 11gr2
11 Things About 11gr2
afa reg
 
PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12
Andrew Dunstan
 
Spring scala - Sneaking Scala into your corporation
Spring scala  - Sneaking Scala into your corporationSpring scala  - Sneaking Scala into your corporation
Spring scala - Sneaking Scala into your corporation
Henryk Konsek
 

Similaire à Android & PostgreSQL (20)

Jdbc
Jdbc Jdbc
Jdbc
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVM
 
Introduction to Compiler Development
Introduction to Compiler DevelopmentIntroduction to Compiler Development
Introduction to Compiler Development
 
GraphQL Relay Introduction
GraphQL Relay IntroductionGraphQL Relay Introduction
GraphQL Relay Introduction
 
Everyday I'm Shuffling - Tips for Writing Better Spark Programs, Strata San J...
Everyday I'm Shuffling - Tips for Writing Better Spark Programs, Strata San J...Everyday I'm Shuffling - Tips for Writing Better Spark Programs, Strata San J...
Everyday I'm Shuffling - Tips for Writing Better Spark Programs, Strata San J...
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
 
A Deep Dive into Query Execution Engine of Spark SQL
A Deep Dive into Query Execution Engine of Spark SQLA Deep Dive into Query Execution Engine of Spark SQL
A Deep Dive into Query Execution Engine of Spark SQL
 
11 Things About 11gr2
11 Things About 11gr211 Things About 11gr2
11 Things About 11gr2
 
Module 5 jdbc.ppt
Module 5   jdbc.pptModule 5   jdbc.ppt
Module 5 jdbc.ppt
 
My java file
My java fileMy java file
My java file
 
JavaFX, because you're worth it
JavaFX, because you're worth itJavaFX, because you're worth it
JavaFX, because you're worth it
 
Code GPU with CUDA - Identifying performance limiters
Code GPU with CUDA - Identifying performance limitersCode GPU with CUDA - Identifying performance limiters
Code GPU with CUDA - Identifying performance limiters
 
Jdbc
JdbcJdbc
Jdbc
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
 
JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020
 
Spring scala - Sneaking Scala into your corporation
Spring scala  - Sneaking Scala into your corporationSpring scala  - Sneaking Scala into your corporation
Spring scala - Sneaking Scala into your corporation
 

Plus de Mark Wong

OHAI, my name is Chelnik! PGCon 2014 Mockumentary
OHAI, my name is Chelnik! PGCon 2014 MockumentaryOHAI, my name is Chelnik! PGCon 2014 Mockumentary
OHAI, my name is Chelnik! PGCon 2014 Mockumentary
Mark Wong
 
Introduction to PostgreSQL
Introduction to PostgreSQLIntroduction to PostgreSQL
Introduction to PostgreSQL
Mark Wong
 

Plus de Mark Wong (20)

OHAI, my name is Chelnik! PGCon 2014 Mockumentary
OHAI, my name is Chelnik! PGCon 2014 MockumentaryOHAI, my name is Chelnik! PGCon 2014 Mockumentary
OHAI, my name is Chelnik! PGCon 2014 Mockumentary
 
OHAI, my name is Chelnik! Postgres Open 2013 Report
OHAI, my name is Chelnik! Postgres Open 2013 ReportOHAI, my name is Chelnik! Postgres Open 2013 Report
OHAI, my name is Chelnik! Postgres Open 2013 Report
 
collectd & PostgreSQL
collectd & PostgreSQLcollectd & PostgreSQL
collectd & PostgreSQL
 
Introduction to PostgreSQL
Introduction to PostgreSQLIntroduction to PostgreSQL
Introduction to PostgreSQL
 
Developing PGTop for Android
Developing PGTop for AndroidDeveloping PGTop for Android
Developing PGTop for Android
 
Pg in-the-brazilian-armed-forces-presentation
Pg in-the-brazilian-armed-forces-presentationPg in-the-brazilian-armed-forces-presentation
Pg in-the-brazilian-armed-forces-presentation
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
PostgreSQL Portland Performance Practice Project - Database Test 2 Tuning
PostgreSQL Portland Performance Practice Project - Database Test 2 TuningPostgreSQL Portland Performance Practice Project - Database Test 2 Tuning
PostgreSQL Portland Performance Practice Project - Database Test 2 Tuning
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
Filesystem Performance from a Database Perspective
Filesystem Performance from a Database PerspectiveFilesystem Performance from a Database Perspective
Filesystem Performance from a Database Perspective
 
PostgreSQL Portland Performance Practice Project - Database Test 2 Filesystem...
PostgreSQL Portland Performance Practice Project - Database Test 2 Filesystem...PostgreSQL Portland Performance Practice Project - Database Test 2 Filesystem...
PostgreSQL Portland Performance Practice Project - Database Test 2 Filesystem...
 
PostgreSQL Portland Performance Practice Project - Database Test 2 Howto
PostgreSQL Portland Performance Practice Project - Database Test 2 HowtoPostgreSQL Portland Performance Practice Project - Database Test 2 Howto
PostgreSQL Portland Performance Practice Project - Database Test 2 Howto
 
PostgreSQL Portland Performance Practice Project - Database Test 2 Workload D...
PostgreSQL Portland Performance Practice Project - Database Test 2 Workload D...PostgreSQL Portland Performance Practice Project - Database Test 2 Workload D...
PostgreSQL Portland Performance Practice Project - Database Test 2 Workload D...
 
PostgreSQL Portland Performance Practice Project - Database Test 2 Background
PostgreSQL Portland Performance Practice Project - Database Test 2 BackgroundPostgreSQL Portland Performance Practice Project - Database Test 2 Background
PostgreSQL Portland Performance Practice Project - Database Test 2 Background
 
PostgreSQL Portland Performance Practice Project - Database Test 2 Series Ove...
PostgreSQL Portland Performance Practice Project - Database Test 2 Series Ove...PostgreSQL Portland Performance Practice Project - Database Test 2 Series Ove...
PostgreSQL Portland Performance Practice Project - Database Test 2 Series Ove...
 
pg_top is 'top' for PostgreSQL: pg_top + pg_proctab
pg_top is 'top' for PostgreSQL: pg_top + pg_proctabpg_top is 'top' for PostgreSQL: pg_top + pg_proctab
pg_top is 'top' for PostgreSQL: pg_top + pg_proctab
 
Linux Filesystems, RAID, and more
Linux Filesystems, RAID, and moreLinux Filesystems, RAID, and more
Linux Filesystems, RAID, and more
 
pg_top is 'top' for PostgreSQL
pg_top is 'top' for PostgreSQLpg_top is 'top' for PostgreSQL
pg_top is 'top' for PostgreSQL
 
What Is Going On?
What Is Going On?What Is Going On?
What Is Going On?
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Dernier (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

Android & PostgreSQL

  • 1. Android & PostgreSQL Mark Wong markwkm@postgresql.org PGCon 2011, University of Ottawa 20 May 2011
  • 2. __ __ / ~~~/ . o O ( Hello! ) ,----( oo ) / __ __/ /| ( |( ^ /___ / | |__| |__|-" Slides available at http://www.sideshare.net/markwkm markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 2 / 37
  • 3. Overview Two topics, mostly the latter: • Development environment specific for PostgreSQL JDBC • Code samples for using the PostgreSQL JDBC driver Any requests? markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 3 / 37
  • 4. Audience Survey Are you familiar with: • Developed an Android application? • Java? • JDBC? • Eclipse? • SQL? • PostgreSQL? markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 4 / 37
  • 5. Development Environment A few details on the following slides about: • JDK5 or JDK6 • Android SDK • PostgreSQL JDBC Driver • Eclipse is optional, current Android SDK r11 requires 3.5 or 3.6 Full system requirement details for Android development: http://developer.android.com/sdk/requirements.html markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 5 / 37
  • 6. PostgreSQL JDBC Driver http://jdbc.postgresql.org/ • Distributed under BSD License. (http://jdbc.postgresql.org/license.html) • Supports PostgreSQL 7.2 and laster version • Thread-safe (http://jdbc.postgresql.org/documentation/head/thread.html) • JDBC3 vs. JDBC4 (http://jdbc.postgresql.org/download.html) • If you are using the 1.6 JVM, then you should use the JDBC4 version. • JDK 1.4, 1.5 - JDBC 3. This contains support for SSL and javax.sql, but does not require J2EE as it has been added to the J2SE release. • JDK 1.6 - JDBC4. Support for JDBC4 methods is limited. The driver builds, but the several of the new methods are stubbed out. • Todo list http://jdbc.postgresql.org/todo.html markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 6 / 37
  • 7. Using the PostgreSQL JDBC Driver To add the PostgreSQL JDBC driver for building and packaging edit the hidden .classpath file at the top level of the project directory with the full path to the JAR file: < c l a s s p a t h> ... < c l a s s p a t h e n t r y k i n d=” l i b ” p a t h=”/ w o r k s p a c e / p r o j / p o s t g r e s q l −9.0 −801. j d b c 4 . j a r ”/> ... </ c l a s s p a t h> Alternate instructions when using Eclipse: http://developer.android.com/resources/faq/commontasks.html#addexternallibrary markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 7 / 37
  • 8. PostgreSQL JDBC Version Notes Dave Cramer built a special version of the PostgreSQL JDBC driver that works on Android 1.5 and later and posted it in a discussion in the PgAndroid Google Group (this pdf should be built so you can click on the tiny text to open the link): http://groups.google.com/group/pgandroid/browse_thread/thread/d8b400f039f66d5f/f77b2e2a99370a36?lnk=raot#f77b2e2a99370a36 At this time, build 801 of the JDBC driver works with Android 2.1 and later. markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 8 / 37
  • 9. PostgreSQL JDBC Code Examples • Some simple examples for connecting to a PostgreSQL database and querying some data, and PostgreSQL specific features • Most examples are variations of those given in the PostgreSQL and PostgreSQL JDBC documentation Warning: code formatted to fit better on these slides. . . markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 9 / 37
  • 10. Open a Database Connection Load the PostgreSQL JDBC driver and open a database connection using SSL: C l a s s . forName ( ” o r g . p o s t g r e s q l . D r i v e r ” ) ; String url ; u r l = ” jdbc : p o s t g r e s q l :// pghost :5432/ pgdatabase ” + ” ? s s l f a c t o r y =o r g . p o s t g r e s q l . s s l . N o n V a l i d a t i n g F a c t o r y ” + ”& s s l =t r u e ” ; C o n n e c t i o n conn = D r i v e r M a n a g e r . g e t C o n n e c t i o n ( u r l , ” pguser ” , ” pgpass ” ) ; // Don ’ t f o r g e t t o c l o s e t h e c o n n e c t i o n when you ’ r e done . // conn . c l o s e ( ) ; markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 10 / 37
  • 11. Execute a Query Select the name of all relations from pg class and iterate through every row returned: String sql ; s q l = ”SELECT r e l n a m e FROM p g c l a s s WHERE r e l k i n d = ’ r ’ ; ” S t a t e m e n t s t = conn . c r e a t e S t a t e m e n t ( ) ; ResultSet r s = st . executeQuery ( s q l ) ; while ( r s . next ( ) ) { // Columns a r e can be r e f e r e n c e d by name . S t r i n g relname = r s . g e t S t r i n g ( ” relname ” ) ; } rs . close (); st . close (); markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 11 / 37
  • 12. Execute a Query Using a Cursor Select the name of all table names from pg tables and iterate through them fetching 10 at a time: conn . setAutoCommit ( f a l s e ) ; S t r i n g s q l = ”SELECT t a b l e n a m e FROM p g t a b l e s ; ” S t a t e m e n t s t = conn . c r e a t e S t a t e m e n t ( ) ; st . setFetchSize (10); ResultSet r s = st . executeQuery ( s q l ) ; while ( r s . next ( ) ) { // Columns a r e can be r e f e r e n c e d by name . S t r i n g relname = r s . g e t S t r i n g ( ” relname ” ) ; } rs . close (); st . close (); markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 12 / 37
  • 13. Execute a Query with a Bind Value Building on the previous slide, select the number of all relations from pg class: S t r i n g s q l = ”SELECT COUNT( ∗ ) FROM p g c l a s s WHERE r e l k i n d = ? ; ” P r e p a r e d S t a t e m e n t ps = conn . c r e a t e S t a t e m e n t ( ) ; // Bind v a r i a b l e s a r e e n u m e r a t e d s t a r t i n g w i t h 1 ; ps . s e t S t r i n g ( 1 , ” r ” ) ; R e s u l t S e t r s = ps . e x e c u t e Q u e r y ( s q l ) ; rs . next ( ) ; Columns a r e e n u m e r a t e d s t a r t i n g w i t h 1 . long c o u n t = r s . g e t L o n g ( 1 ) ; rs . close (); ps . c l o s e ( ) ; markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 13 / 37
  • 14. Some addition methods for retrieving column data getBoolean () getLong ( ) getDate () getShort () getDouble () getString () getFloat () getTime ( ) getInt () getTimestamp ( ) markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 14 / 37
  • 15. Create, Modify, or Drop Database Objects Execute CREATE, ALTER, or DROP SQL statements with the execute() method: S t a t e m e n t s t = conn . c r e a t e S t a t e m e n t ( ) ; s t . e x e c u t e ( ”CREATE TABLE f i l m s ( t i t l e VARCHAR ( 4 0 ) ; ” ) ; st . close (); markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 15 / 37
  • 16. Example for INSERT, UPDATE and DELETE Executing INSERT, UPDATE, or DELETE SQL statements use the executeUpdate() as opposed to the executeQuery() method shown previously with SELECT statements. Also, executeUpdate() returns the number of rows affected as opposed to a ResultSet, otherwise usage is mostly the same: PreparedStatement st = conn . p r e p a r e S t a t e m e n t ( ”INSERT INTO f i l m s ( t i t l e ) ” + ”VALUES ( ? ) ; ” ) ; s t . s e t S t r i n g ( 1 , ”On S t r a n g e r T i d e s ” ) ; i n t rows = s t . e x e c u t e U p d a t e ( ) ; st . close (); markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 16 / 37
  • 17. Example for Calling Stored Functions Call a built-in stored function that returns a value. In this example, call upper() to change a string to all upper case characters: CallableStatement upperProc = conn . p r e p a r e C a l l ( ”{ ? = c a l l u p p e r ( ? ) }” ) ; u p p e r P r o c . r e g i s t e r O u t P a r a m e t e r ( 1 , Types . VARCHAR ) ; upperProc . s e t S t r i n g (2 , ” lowercase to uppercase ” ) ; upperProc . execute ( ) ; S t r i n g upperCased = upperProc . g e t S t r i n g ( 1 ) ; upperProc . c l o s e ( ) ; markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 17 / 37
  • 18. LISTEN & NOTIFY & UNLISTEN http://jdbc.postgresql.org/documentation/head/listennotify.html markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 18 / 37
  • 19. Starting listening to a channel Register this session as a listener to the notification channel virtual: S t a t e m e n t stmt = conn . c r e a t e S t a t e m e n t ( ) ; stmt . e x e c u t e ( ”LISTEN v i r t u a l ; ” ) ; stmt . c l o s e ( ) ; markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 19 / 37
  • 20. LISTEN: Dummy query Need to issue a dummy query to contact the PostgreSQL database before any pending notifications are received: while ( true ) { try { S t a t e m e n t stmt = conn . c r e a t e S t a t e m e n t ( ) ; R e s u l t S e t r s = stmt . e x e c u t e Q u e r y ( ”SELECT 1 ; ” ) ; rs . close (); stmt . c l o s e ( ) ; ... markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 20 / 37
  • 21. LISTEN: Handle notifications A key limitation of the JDBC driver is that it cannot receive asynchronous notifications and must poll the backend to check if any notifications were issued. ... org . p o s t g r e s q l . PGNotification n o t i f i c a t i o n s [ ] = pgconn . g e t N o t i f i c a t i o n s ( ) ; i f ( n o t i f i c a t i o n s != n u l l ) { f o r ( i n t i =0; i < n o t i f i c a t i o n s . l e n g t h ; i ++) { // Handle h e r e : n o t i f i c a t i o n s [ i ] . getName ( ) ) ; } } // Wait b e f o r e c h e c k i n g f o r more n o t i f i c a t i o n s . Thread . s l e e p ( 5 0 0 ) ; ... markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 21 / 37
  • 22. LISTEN: Java Exception Handling ... } catch ( SQLException s q l e ) { sqle . printStackTrace (); } catch ( I n t e r r u p t e d E x c e p t i o n i e ) { ie . printStackTrace (); } } markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 22 / 37
  • 23. Stop listening to a channel Stop listening to the channel virtual: S t a t e m e n t stmt = conn . c r e a t e S t a t e m e n t ( ) ; stmt . e x e c u t e ( ”UNLISTEN v i r t u a l ; ” ) ; stmt . c l o s e ( ) ; markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 23 / 37
  • 24. NOTIFY: Send a notification Send a notification to the channel virtual: S t a t e m e n t stmt = conn . c r e a t e S t a t e m e n t ( ) ; stmt . e x e c u t e ( ”NOTIFY v i r t u a l ; ” ) ; stmt . c l o s e ( ) ; Note: Starting with PostgreSQL 9.0, there is the stored function pg notify(text, text) that can be used. markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 24 / 37
  • 25. Server Prepared Statements JDBC allows a threshold to be set before the server prepared statement is used. Recommended to use with PostgreSQL 7.4 and later: http://jdbc.postgresql.org/documentation/81/server-prepare.html P r e p a r e d S t a t e m e n t pstmt = conn . p r e p a r e S t a t e m e n t ( ”SELECT ? ; ” ) ; // C a s t t h e P r e p a r e d S t a t e m e n t t o t h e PostgreSQL s p e c i f i c // PGStatement . o r g . p o s t g r e s q l . PGStatement pgstmt = ( o r g . p o s t g r e s q l . PGStatement ) pstmt ; // Use p r e p a r e d s t a t e m e n t on t h e 2 nd e x e c u t i o n onward . pgstmt . s e t P r e p a r e T h r e s h o l d ( 2 ) ; pstmt . s e t I n t ( 1 , 4 2 ) ; R e s u l t S e t r s = pstmt . e x e c u t e Q u e r y ( ) ; pstmt . c l o s e ( ) ; markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 25 / 37
  • 26. Geometric data types PostgreSQL data types that include single points, lines, and polygons: http://jdbc.postgresql.org/documentation/81/geometric.html Circle example: stmt . e x e c u t e ( ”CREATE TABLE geo ( m y c i r c c i r c l e ) ; ” ) ; markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 26 / 37
  • 27. INSERT a circle PGpoint c e n t e r = new PGpoint ( 1 , 2 . 5 ) ; double r a d i u s = 4 ; P G c i r c l e c i r c l e = new P G c i r c l e ( c e n t e r , r a d i u s ) ; P r e p a r e d S t a t e m e n t ps = conn . p r e p a r e S t a t e m e n t ( ”INSERT INTO g e o m t e s t ( m y c i r c ) VALUES ( ? ) ; ” ) ; ps . s e t O b j e c t ( 1 , c i r c l e ) ; ps . e x e c u t e U p d a t e ( ) ; markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 27 / 37
  • 28. SELECT a circle R e s u l t S e t r s = stmt . e x e c u t e Q u e r y ( ”SELECT m y c i r c FROM geo ; ” ) ; rs . next ( ) ; PGcircle c i r c l e = ( PGcircle ) rs . getObject (1); PGpoint c e n t e r = c i r c l e . c e n t e r ; double r a d i u s = c i r c l e . r a d i u s ; markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 28 / 37
  • 29. JDBC Escapes A special escape syntax that is JDBC specific and database agnostic: http://jdbc.postgresql.org/documentation/head/escapes.html Dates and timestamps: s t . e x e c u t e Q u e r y ( ”SELECT { f n week ({ d ’2005 −01 −24 ’})}; ” ) ; st . executeQuery ( ”SELECT { f n week ({ t s ’2005−01−24 1 2 : 1 3 : 1 4 . 1 5 ’ } ) } ; ” ) ; Joins: st . executeQuery ( ”SELECT ∗ FROM { o j a LEFT OUTER JOIN b ON ( a . i = b . i ) } ; ” ) ; Scalar functions: s t . e x e c u t e Q u e r y ( ”SELECT { f n a b s ( −1)}; ” ) ; markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 29 / 37
  • 30. Handling binary data Long examples for using the bytea data type and Large Objects: http://jdbc.postgresql.org/documentation/head/binary-data.html markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 30 / 37
  • 31. Connection pools Long examples for using JDBC connection pooling: http://jdbc.postgresql.org/documentation/head/datasource.html markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 31 / 37
  • 32. Example application PGTop for Android is a complete application implementing some of the examples shown here: • Source code: https://github.com/markwkm/pgtop • Android Market: https://market.android.com/details?id=org.postgresql.top markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 32 / 37
  • 33. Android Example Programs For reference, since not covered in this presentation: • Hello, World (includes example without using Eclipse) http://developer.android.com/resources/tutorials/hello-world.html • More examples without using Eclipse http: //developer.android.com/guide/developing/other-ide.html • Even more sample applications http://developer.android.com/resources/samples/ markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 33 / 37
  • 34. Further JDBC Reading JDBC API Documentation and JDBC Specification http://jdbc.postgresql.org/documentation/head/reading.html markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 34 / 37
  • 35. __ __ / ~~~/ . o O ( Thank you! ) ,----( oo ) / __ __/ /| ( |( ^ /___ / | |__| |__|-" markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 35 / 37
  • 36. Acknowledgements Hayley Jane Wakenshaw __ __ / ~~~/ ,----( oo ) / __ __/ /| ( |( ^ /___ / | |__| |__|-" markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 36 / 37
  • 37. License This work is licensed under a Creative Commons Attribution 3.0 Unported License. To view a copy of this license, (a) visit http://creativecommons.org/licenses/by/3.0/us/; or, (b) send a letter to Creative Commons, 171 2nd Street, Suite 300, San Francisco, California, 94105, USA. markwkm (PGCon2011) Android & PostgreSQL 20 May 2011 37 / 37