SlideShare a Scribd company logo
1 of 5
Download to read offline
Download                                                                 JDBC Goals
                                                                   `       Download PostgresSQL                                             `       SQL Level
                                                                           `   http://www.postgresql.org/download/                          `       100% Pure Java
                                                                                                                                            `       Keep it simple
                                                                   `       Download jdbc driver for PostgresSQL                             `       High performance
                                                                           `   http://jdbc.postgresql.org/download.html                     `       Leverage existing database technology
                                                                                                                                                    `   why reinvent the wheel?
                                            Basi di Dati           `       Create database                                                  `       Use strong, static typing wherever possible
                                                                           `   Esami                                                        `       Use multiple methods to express multiple functionality
                                                                   `       Create
                                                     jdbc
                                                                           `   User ‘user’, Password ‘pw’


                                                                       3                                                             jdbc       4                                                                   jdbc




JDBC Architecture                                                  java.sql                                                                 DriverManager
`       Java code calls JDBC library                               `       JDBC is implemented via classes in the java.sql package          `       DriverManager tries all the drivers
`       JDBC loads a driver                                                                                                                 `       Uses the first one that works
`       Driver talks to a particular database                                                                                               `       When a driver class is first loaded, it registers itself with
                                                                                                                                                    the DriverManager
`       Can have more than one driver > more than one
                                                                                                                                            `       Therefore, to register a driver, just load it!
        database
`       Ideal: can change database engines without changing
        any application code

          Application      JDBC          Driver



    5                                                       jdbc       6                                                             jdbc       7                                                                   jdbc
Registering a Driver                                                  JDBC Object Classes                                                          JDBC Class Usage
`       Statically load driver                                        `       DriverManager
                                                                              `   Loads, chooses drivers                                           DriverManager
Class.forName(“org.postgresql.Driver”);                               `       Driver
Connection c =                                                                `   connects to actual database                                                           Driver
  DriverManager.getConnection(...);                                   `       Connection
                                                                              `   a series of SQL statements to and from the DB                                                  Connection

                                                                      `       Statement/PreparedStatement
                                                                                                                                                                                                        Statement
                                                                              `   a single SQL statement
                                                                      `       ResultSet                                                                                                  PreparedStatement
                                                                              `   the records returned from a Statement/PreparedStatement
                                                                                                                                                                                                                    ResultSet

    8                                                          jdbc       9                                                                 jdbc       10                                                                       jdbc




JDBC URLs                                                             DriverManager                                                                Connection
jdbc:subprotocol:source                                               Connection getConnection                                                     `    A Connection represents a session with a specific database.
                                                                        (String url, String user, String password)
                                                                                                                                                   `    Within the context of a Connection, SQL statements are
`       each driver has its own subprotocol                                                                                                             executed and results are returned.
`       each subprotocol has its own syntax for the source            `       Connects to given JDBC URL with given user name and
                                                                              password                                                             `    Can have multiple connections to a database
                                                                                                                                                        `   NB: Some drivers don’t support serialized connections
jdbc:odbc:DataSource                                                  `       Throws java.sql.SQLException                                              `   Fortunately, most do (now)
        `   e.g. jdbc:odbc:Northwind                                  `       Returns a Connection object
jdbc:mysql://host[:port]/database                                                                                                                  `    Also provides “metadata” information about the database,
                                                                                                                                                        tables, and fields
        `   e.g. jdbc:msql://foo.nowhere.com:4333/accounting
jdbc:postgresql://host:port/database                                                                                                               `    Also methods to deal with transactions
        `   e.g. jdbc:postgresql://localhost:5432/esami

    11                                                         jdbc       12                                                                jdbc       13                                                                       jdbc
Obtaining a Connection                                                      Connection Methods                                                     Statement
try{                                                                        Statement createStatement()                                            `    A Statement object is used for executing a static SQL
     Class.forName (quot;org.postgresql.Driverquot;);   // Load the Driver
                                                                              `   returns a new Statement object
     Connection conn = DriverManager.getConnection
                                                                                                                                                        statement and obtaining the results produced by it.
          (quot;jdbc:postgresql://localhost:5432/esamiquot;, quot;userquot;, quot;pwquot; );
     Statement stmt = conn.createStatement();                               PreparedStatement prepareStatement(String sql)
     //...                                                                    `   returns a new PreparedStatement object
     stmt.close();
     conn.close();
}
catch (ClassNotFoundException e) {
     e.printStackTrace();
}
catch (SQLException e) {
     e.printStackTrace();
}


    14                                                               jdbc    15                                                             jdbc       16                                                          jdbc




Statement Methods                                                           Statement Methods                                                      ResultSet
ResultSet executeQuery(String)                                              ...                                                                    `    A ResultSet provides access to a table of data generated
  ` Execute a SQL statement that returns a single ResultSet.
                                                                            String sql =                                                                by executing a Statement.
                                                                              quot;CREATE TABLE STUDENTI
                                                                              (matr integer primary key, cognome varchar, nome varchar)quot;;
                                                                            stmt.executeUpdate(sql);
                                                                                                                                                   `    Only one ResultSet per Statement can be open at once.
int executeUpdate(String)
 ` Execute a SQL INSERT, UPDATE or DELETE statement.                        sql =                                                                  `    The table rows are retrieved in sequence.
   Returns the number of rows changed.                                        quot;INSERT INTO STUDENTI VALUES(1, 'rossi', 'mario'),
                                                                                     (2, 'bianchi', 'sergio')quot;;
                                                                                                                                                   `    A ResultSet maintains a cursor pointing to its current row
                                                                            stmt.executeUpdate(sql);
boolean execute(String)                                                                                                                                 of data.
                                                                            sql =
 ` Execute a SQL statement that may return multiple results.
                                                                              quot;SELECT * FROM STUDENTIquot;;                                            `    The 'next' method moves the cursor to the next row.
                                                                            ResultSet rs = stmt.executeQuery(sql);                                      `   you can’t rewind
                                                                            ...


    17                                                               jdbc    18                                                             jdbc       19                                                          jdbc
ResultSet Methods                                                    ResultSet Methods                                            ResultSet Methods
`    boolean next()                                                  `    Type getType(int columnIndex)                           `    String getString(int columnIndex)
     `   activates the next row                                           `   returns the given field as the given type           `    boolean getBoolean(int columnIndex)
     `   the first call to next() activates the first row                 `   fields indexed starting at 1 (not 0)                `    byte getByte(int columnIndex)
     `   returns false if there are no more rows                                                                                  `    short getShort(int columnIndex)
                                                                     `    Type getType(String columnName)
                                                                                                                                  `    int getInt(int columnIndex)
`    void close()                                                         `   same, but uses name of field
                                                                                                                                  `    long getLong(int columnIndex)
     `   disposes of the ResultSet                                        `   less efficient
                                                                                                                                  `    float getFloat(int columnIndex)
     `   allows you to re use the Statement that created it          `    int findColumn(String columnName)
                                                                                                                                  `    double getDouble(int columnIndex)
     `   automatically called by most Statement methods                   `   looks up column index given column name
                                                                                                                                  `    Date getDate(int columnIndex)
                                                                                                                                  `    Time getTime(int columnIndex)
                                                                                                                                  `    Timestamp getTimestamp(int columnIndex)


    20                                                        jdbc       21                                                jdbc       22                                                        jdbc




ResultSet Methods                                                    ResultSet Methods                                            Mapping Java Types to SQL Types
                                                                     ...
`    String getString(String columnName)
                                                                     sql = quot;SELECT * FROM STUDENTIquot;;
`    boolean getBoolean(String columnName)                                                                                            SQL type                           Java Type
                                                                     ResultSet rs = stmt.executeQuery(sql);
`    byte getByte(String columnName)                                                                                                  CHAR, VARCHAR, LONGVARCHAR         String
                                                                                                                                      NUMERIC, DECIMAL                   java.math.BigDecimal
`    short getShort(String columnName)                               while (rs.next()) {                                              BIT                                boolean
                                                                          int matr = rs.getInt(quot;matrquot;);                               TINYINT                            byte
`    int getInt(String columnName)
                                                                          String cognome = rs.getString(quot;cognomequot;);                   SMALLINT                           short
`    long getLong(String columnName)                                                                                                  INTEGER                            int
                                                                          String nome = rs.getString(quot;nomequot;);
`    float getFloat(String columnName)                                    System.out.println(matr+quot; quot;+cognome+quot; quot;+nome);              BIGINT                             long
                                                                                                                                      REAL                               float
`    double getDouble(String columnName)                             }
                                                                                                                                      FLOAT, DOUBLE                      double
                                                                     rs.close();
`    Date getDate(String columnName)                                                                                                  BINARY, VARBINARY, LONGVARBINARY   byte[]
                                                                     stmt.close();                                                    DATE                               java.sql.Date
`    Time getTime(String columnName)                                 ...                                                              TIME                               java.sql.Time
`    Timestamp getTimestamp(String columnName)                                                                                        TIMESTAMP                          java.sql.Timestamp



    23                                                        jdbc       24                                                jdbc       25                                                        jdbc
PreparedStatement motivation                                       PreparedStatement                                                     PreparedStatement
                                                                                                                                         ...
`    Suppose we would like to run the query                        `    PreparedStatement prepareStatement(String)                       sql = quot;SELECT * FROM STUDENTI WHERE nome = ? and matr > ?quot;;
                                                                        `   returns a new PreparedStatement object                       PreparedStatement preparedStatement = conn.prepareStatement(sql);
     SELECT * FROM STUDENTI                                                                                                              preparedStatement.setString(1, quot;sergioquot;);
                                                                                                                                         preparedStatement.setInt(2, 0);
     WHERE name=‘sergio’;                                          `    Prepared Statements are used for queries that are                rs = preparedStatement.executeQuery();
                                                                                                                                         while (rs.next()) {
                                                                        executed many times with possibly different contents.              int matr = rs.getInt(1);
                                                                                                                                           String cognome = rs.getString(2);
                                                                   `    A PreparedStatement object includes the query and is
`    But we would like to run this for all students                                                                                        String nome = rs.getString(3);
                                                                        prepared for execution (precompiled).                              System.out.println(matr+quot; quot;+cognome+quot; quot;+nome);
     (separately), not only ‘sergio’…                              `    Question marks can be inserted as variables.                     }
                                                                                                                                         rs.close();
`    Could we create a variable instead of ‘sergio’ which               `   setString(i, value)   The i th question mark is set          preparedStatement.close();
                                                                                                                                         conn.close();
     would get a different name every time??..                          `   setInt(i, value)      to the given value.                    }
                                                                                                                                         ...


    26                                                      jdbc       27                                                         jdbc    28                                                                 jdbc




PreparedStatement                                                  JDBC Class Diagram
`    Will this work?

         PreparedStatement pstmt =
           con.prepareStatement(“select * from ?”);
         pstmt.setString(1, quot;Sailorsquot;);


`    No! We may put ? only instead of values




    29                                                      jdbc       30                                                         jdbc

More Related Content

What's hot

The State of Java under Oracle at JCertif 2011
The State of Java under Oracle at JCertif 2011The State of Java under Oracle at JCertif 2011
The State of Java under Oracle at JCertif 2011Arun Gupta
 
Understanding
Understanding Understanding
Understanding Arun Gupta
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsFulvio Corno
 
GlassFish REST Administration Backend
GlassFish REST Administration BackendGlassFish REST Administration Backend
GlassFish REST Administration BackendArun Gupta
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Pooja Talreja
 
DataBase Connectivity
DataBase ConnectivityDataBase Connectivity
DataBase ConnectivityAkankshaji
 
Running your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the CloudRunning your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the CloudArun Gupta
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivitybackdoor
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database ConnectivityRanjan Kumar
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityAtul Saurabh
 

What's hot (20)

The State of Java under Oracle at JCertif 2011
The State of Java under Oracle at JCertif 2011The State of Java under Oracle at JCertif 2011
The State of Java under Oracle at JCertif 2011
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Understanding
Understanding Understanding
Understanding
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
 
GlassFish REST Administration Backend
GlassFish REST Administration BackendGlassFish REST Administration Backend
GlassFish REST Administration Backend
 
Jdbc connectivity in java
Jdbc connectivity in javaJdbc connectivity in java
Jdbc connectivity in java
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
DataBase Connectivity
DataBase ConnectivityDataBase Connectivity
DataBase Connectivity
 
Running your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the CloudRunning your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the Cloud
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 

Viewers also liked

Viewers also liked (16)

Calc Num Zanni 02
Calc Num Zanni 02Calc Num Zanni 02
Calc Num Zanni 02
 
Basi Dati B5
Basi Dati B5Basi Dati B5
Basi Dati B5
 
Basi Dati C5
Basi Dati C5Basi Dati C5
Basi Dati C5
 
Basi Dati B2
Basi Dati B2Basi Dati B2
Basi Dati B2
 
Art Slide Show
Art Slide ShowArt Slide Show
Art Slide Show
 
Calc Num Prato 03
Calc Num Prato 03Calc Num Prato 03
Calc Num Prato 03
 
Basi Dati C1
Basi Dati C1Basi Dati C1
Basi Dati C1
 
Basi Dati C7
Basi Dati C7Basi Dati C7
Basi Dati C7
 
Basi Dati C2
Basi Dati C2Basi Dati C2
Basi Dati C2
 
Basi Dati A1
Basi Dati A1Basi Dati A1
Basi Dati A1
 
Branch And Network Partner
Branch And Network PartnerBranch And Network Partner
Branch And Network Partner
 
Tally Sheet Results - Technology Habits
Tally Sheet Results - Technology HabitsTally Sheet Results - Technology Habits
Tally Sheet Results - Technology Habits
 
Lessons From The Life Of A.R.Rahman
Lessons From The Life Of A.R.RahmanLessons From The Life Of A.R.Rahman
Lessons From The Life Of A.R.Rahman
 
PUMPS+-
PUMPS+-PUMPS+-
PUMPS+-
 
Aviation disasters due to mechanical failures
Aviation disasters due to mechanical failuresAviation disasters due to mechanical failures
Aviation disasters due to mechanical failures
 
Ship Rudders
Ship RuddersShip Rudders
Ship Rudders
 

Similar to Basi Dati F2

Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingAnton Keks
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity DevAdnani
 
chapter 5 java.pptx
chapter 5  java.pptxchapter 5  java.pptx
chapter 5 java.pptxBekiTube
 
Fundamentals of JDBC
Fundamentals of JDBCFundamentals of JDBC
Fundamentals of JDBCJainul Musani
 
Jdbc session01
Jdbc session01Jdbc session01
Jdbc session01Niit Care
 
7장 Oracle As Datasource
7장 Oracle As Datasource7장 Oracle As Datasource
7장 Oracle As Datasource김 한도
 
Jsp + My Sql
Jsp + My SqlJsp + My Sql
Jsp + My SqlAshwin K
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdfArumugam90
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdfArumugam90
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
Java session16
Java session16Java session16
Java session16Niit Care
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connectionPaneliya Prince
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connectionPaneliya Prince
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 

Similar to Basi Dati F2 (20)

Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
chapter 5 java.pptx
chapter 5  java.pptxchapter 5  java.pptx
chapter 5 java.pptx
 
Fundamentals of JDBC
Fundamentals of JDBCFundamentals of JDBC
Fundamentals of JDBC
 
Jdbc session01
Jdbc session01Jdbc session01
Jdbc session01
 
7장 Oracle As Datasource
7장 Oracle As Datasource7장 Oracle As Datasource
7장 Oracle As Datasource
 
Jsp + My Sql
Jsp + My SqlJsp + My Sql
Jsp + My Sql
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java session16
Java session16Java session16
Java session16
 
Jdbc
JdbcJdbc
Jdbc
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connection
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connection
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
JDBC
JDBCJDBC
JDBC
 

More from Bombers Falcoman (20)

Calc Num Prato 04
Calc Num Prato 04Calc Num Prato 04
Calc Num Prato 04
 
Calc Num Prato 02
Calc Num Prato 02Calc Num Prato 02
Calc Num Prato 02
 
Calc Num Prato 01(21.05.09)
Calc Num Prato 01(21.05.09)Calc Num Prato 01(21.05.09)
Calc Num Prato 01(21.05.09)
 
Calc Num Es 13.05.09
Calc Num Es 13.05.09Calc Num Es 13.05.09
Calc Num Es 13.05.09
 
Basi Dati F1 Es
Basi Dati F1 EsBasi Dati F1 Es
Basi Dati F1 Es
 
Basi Dati F1 Bis
Basi Dati F1 BisBasi Dati F1 Bis
Basi Dati F1 Bis
 
Basi Dati E6
Basi Dati E6Basi Dati E6
Basi Dati E6
 
Basi Dati E5
Basi Dati E5Basi Dati E5
Basi Dati E5
 
Basi Dati E3
Basi Dati E3Basi Dati E3
Basi Dati E3
 
Basi Dati E1
Basi Dati E1Basi Dati E1
Basi Dati E1
 
Basi Dati F1
Basi Dati F1Basi Dati F1
Basi Dati F1
 
Basi Dati E2
Basi Dati E2Basi Dati E2
Basi Dati E2
 
Basi Dati E4
Basi Dati E4Basi Dati E4
Basi Dati E4
 
Basi Dati C Riepilogo
Basi Dati C RiepilogoBasi Dati C Riepilogo
Basi Dati C Riepilogo
 
Basi Dati C5 Es
Basi Dati C5 EsBasi Dati C5 Es
Basi Dati C5 Es
 
Basi Dati C6
Basi Dati C6Basi Dati C6
Basi Dati C6
 
Basi Dati C6 Es
Basi Dati C6 EsBasi Dati C6 Es
Basi Dati C6 Es
 
Basi Dati d4
Basi Dati d4Basi Dati d4
Basi Dati d4
 
Basi Dati d3
Basi Dati d3Basi Dati d3
Basi Dati d3
 
Basi Dati d2
Basi Dati d2Basi Dati d2
Basi Dati d2
 

Recently uploaded

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
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 WorkerThousandEyes
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 

Recently uploaded (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
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
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

Basi Dati F2

  • 1. Download JDBC Goals ` Download PostgresSQL ` SQL Level ` http://www.postgresql.org/download/ ` 100% Pure Java ` Keep it simple ` Download jdbc driver for PostgresSQL ` High performance ` http://jdbc.postgresql.org/download.html ` Leverage existing database technology ` why reinvent the wheel? Basi di Dati ` Create database ` Use strong, static typing wherever possible ` Esami ` Use multiple methods to express multiple functionality ` Create jdbc ` User ‘user’, Password ‘pw’ 3 jdbc 4 jdbc JDBC Architecture java.sql DriverManager ` Java code calls JDBC library ` JDBC is implemented via classes in the java.sql package ` DriverManager tries all the drivers ` JDBC loads a driver ` Uses the first one that works ` Driver talks to a particular database ` When a driver class is first loaded, it registers itself with the DriverManager ` Can have more than one driver > more than one ` Therefore, to register a driver, just load it! database ` Ideal: can change database engines without changing any application code Application JDBC Driver 5 jdbc 6 jdbc 7 jdbc
  • 2. Registering a Driver JDBC Object Classes JDBC Class Usage ` Statically load driver ` DriverManager ` Loads, chooses drivers DriverManager Class.forName(“org.postgresql.Driver”); ` Driver Connection c = ` connects to actual database Driver DriverManager.getConnection(...); ` Connection ` a series of SQL statements to and from the DB Connection ` Statement/PreparedStatement Statement ` a single SQL statement ` ResultSet PreparedStatement ` the records returned from a Statement/PreparedStatement ResultSet 8 jdbc 9 jdbc 10 jdbc JDBC URLs DriverManager Connection jdbc:subprotocol:source Connection getConnection ` A Connection represents a session with a specific database. (String url, String user, String password) ` Within the context of a Connection, SQL statements are ` each driver has its own subprotocol executed and results are returned. ` each subprotocol has its own syntax for the source ` Connects to given JDBC URL with given user name and password ` Can have multiple connections to a database ` NB: Some drivers don’t support serialized connections jdbc:odbc:DataSource ` Throws java.sql.SQLException ` Fortunately, most do (now) ` e.g. jdbc:odbc:Northwind ` Returns a Connection object jdbc:mysql://host[:port]/database ` Also provides “metadata” information about the database, tables, and fields ` e.g. jdbc:msql://foo.nowhere.com:4333/accounting jdbc:postgresql://host:port/database ` Also methods to deal with transactions ` e.g. jdbc:postgresql://localhost:5432/esami 11 jdbc 12 jdbc 13 jdbc
  • 3. Obtaining a Connection Connection Methods Statement try{ Statement createStatement() ` A Statement object is used for executing a static SQL Class.forName (quot;org.postgresql.Driverquot;); // Load the Driver ` returns a new Statement object Connection conn = DriverManager.getConnection statement and obtaining the results produced by it. (quot;jdbc:postgresql://localhost:5432/esamiquot;, quot;userquot;, quot;pwquot; ); Statement stmt = conn.createStatement(); PreparedStatement prepareStatement(String sql) //... ` returns a new PreparedStatement object stmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } 14 jdbc 15 jdbc 16 jdbc Statement Methods Statement Methods ResultSet ResultSet executeQuery(String) ... ` A ResultSet provides access to a table of data generated ` Execute a SQL statement that returns a single ResultSet. String sql = by executing a Statement. quot;CREATE TABLE STUDENTI (matr integer primary key, cognome varchar, nome varchar)quot;; stmt.executeUpdate(sql); ` Only one ResultSet per Statement can be open at once. int executeUpdate(String) ` Execute a SQL INSERT, UPDATE or DELETE statement. sql = ` The table rows are retrieved in sequence. Returns the number of rows changed. quot;INSERT INTO STUDENTI VALUES(1, 'rossi', 'mario'), (2, 'bianchi', 'sergio')quot;; ` A ResultSet maintains a cursor pointing to its current row stmt.executeUpdate(sql); boolean execute(String) of data. sql = ` Execute a SQL statement that may return multiple results. quot;SELECT * FROM STUDENTIquot;; ` The 'next' method moves the cursor to the next row. ResultSet rs = stmt.executeQuery(sql); ` you can’t rewind ... 17 jdbc 18 jdbc 19 jdbc
  • 4. ResultSet Methods ResultSet Methods ResultSet Methods ` boolean next() ` Type getType(int columnIndex) ` String getString(int columnIndex) ` activates the next row ` returns the given field as the given type ` boolean getBoolean(int columnIndex) ` the first call to next() activates the first row ` fields indexed starting at 1 (not 0) ` byte getByte(int columnIndex) ` returns false if there are no more rows ` short getShort(int columnIndex) ` Type getType(String columnName) ` int getInt(int columnIndex) ` void close() ` same, but uses name of field ` long getLong(int columnIndex) ` disposes of the ResultSet ` less efficient ` float getFloat(int columnIndex) ` allows you to re use the Statement that created it ` int findColumn(String columnName) ` double getDouble(int columnIndex) ` automatically called by most Statement methods ` looks up column index given column name ` Date getDate(int columnIndex) ` Time getTime(int columnIndex) ` Timestamp getTimestamp(int columnIndex) 20 jdbc 21 jdbc 22 jdbc ResultSet Methods ResultSet Methods Mapping Java Types to SQL Types ... ` String getString(String columnName) sql = quot;SELECT * FROM STUDENTIquot;; ` boolean getBoolean(String columnName) SQL type Java Type ResultSet rs = stmt.executeQuery(sql); ` byte getByte(String columnName) CHAR, VARCHAR, LONGVARCHAR String NUMERIC, DECIMAL java.math.BigDecimal ` short getShort(String columnName) while (rs.next()) { BIT boolean int matr = rs.getInt(quot;matrquot;); TINYINT byte ` int getInt(String columnName) String cognome = rs.getString(quot;cognomequot;); SMALLINT short ` long getLong(String columnName) INTEGER int String nome = rs.getString(quot;nomequot;); ` float getFloat(String columnName) System.out.println(matr+quot; quot;+cognome+quot; quot;+nome); BIGINT long REAL float ` double getDouble(String columnName) } FLOAT, DOUBLE double rs.close(); ` Date getDate(String columnName) BINARY, VARBINARY, LONGVARBINARY byte[] stmt.close(); DATE java.sql.Date ` Time getTime(String columnName) ... TIME java.sql.Time ` Timestamp getTimestamp(String columnName) TIMESTAMP java.sql.Timestamp 23 jdbc 24 jdbc 25 jdbc
  • 5. PreparedStatement motivation PreparedStatement PreparedStatement ... ` Suppose we would like to run the query ` PreparedStatement prepareStatement(String) sql = quot;SELECT * FROM STUDENTI WHERE nome = ? and matr > ?quot;; ` returns a new PreparedStatement object PreparedStatement preparedStatement = conn.prepareStatement(sql); SELECT * FROM STUDENTI preparedStatement.setString(1, quot;sergioquot;); preparedStatement.setInt(2, 0); WHERE name=‘sergio’; ` Prepared Statements are used for queries that are rs = preparedStatement.executeQuery(); while (rs.next()) { executed many times with possibly different contents. int matr = rs.getInt(1); String cognome = rs.getString(2); ` A PreparedStatement object includes the query and is ` But we would like to run this for all students String nome = rs.getString(3); prepared for execution (precompiled). System.out.println(matr+quot; quot;+cognome+quot; quot;+nome); (separately), not only ‘sergio’… ` Question marks can be inserted as variables. } rs.close(); ` Could we create a variable instead of ‘sergio’ which ` setString(i, value) The i th question mark is set preparedStatement.close(); conn.close(); would get a different name every time??.. ` setInt(i, value) to the given value. } ... 26 jdbc 27 jdbc 28 jdbc PreparedStatement JDBC Class Diagram ` Will this work? PreparedStatement pstmt = con.prepareStatement(“select * from ?”); pstmt.setString(1, quot;Sailorsquot;); ` No! We may put ? only instead of values 29 jdbc 30 jdbc