SlideShare une entreprise Scribd logo
1  sur  36
Introducing JDBC


Objectives
    In this lesson, you will learn about:


         •   Layers in JDBC architecture
         •   Types of JDBC drivers
         •   Classes and interfaces of JDBC API
         •   Steps to create JDBC applications




 ©NIIT                    JDBC and JavaBeans      Lesson 1A / Slide 1 of 36
Introducing JDBC


Database Connectivity
    •    Sun Microsystems has included JDBC API as a part of J2SDK to develop Java
         applications that can communicate with databases.
    •    The following figure shows the Airline Reservation System developed in Java
         interacting with the Airlines database using the JDBC API:




 ©NIIT                     JDBC and JavaBeans                Lesson 1A / Slide 2 of 36
Introducing JDBC


Database Connectivity (Contd.)
    •    JDBC Architecture:
           • Provides the mechanism to translate Java statements into SQL
             statements.
           • Can be classified into two layers:
                • JDBC application layer
                • JDBC driver layer




 ©NIIT                    JDBC and JavaBeans                Lesson 1A / Slide 3 of 36
Introducing JDBC


Database Connectivity (Contd.)
    •    JDBC Drivers:
           • Convert SQL statements into a form that a particular database can
             interpret.
           • Retrieve the result of SQL statements and convert the result into
             equivalent JDBC API class objects.
           • Are of four types:
                • JDBC-ODBC Bridge driver
                • Native-API Partly-Java driver
                • JDBC-Net Pure-Java driver
                • Native Protocol Pure-Java driver




 ©NIIT                     JDBC and JavaBeans                Lesson 1A / Slide 4 of 36
Introducing JDBC


Database Connectivity (Contd.)
    •    JDBC-ODBC Bridge driver




 ©NIIT                   JDBC and JavaBeans   Lesson 1A / Slide 5 of 36
Introducing JDBC


Database Connectivity (Contd.)
    •    Native-API Partly-Java driver




 ©NIIT                   JDBC and JavaBeans   Lesson 1A / Slide 6 of 36
Introducing JDBC


Database Connectivity (Contd.)
    •    JDBC-Net Pure-Java driver




 ©NIIT                  JDBC and JavaBeans   Lesson 1A / Slide 7 of 36
Introducing JDBC


Database Connectivity (Contd.)
    •    Native-Protocol Pure-Java driver




 ©NIIT                   JDBC and JavaBeans   Lesson 1A / Slide 8 of 36
Introducing JDBC


Using JDBC API
    •    The JDBC API classes and interfaces are available in the java.sql and the
         javax.sql packages.


    •    The commonly used classes and interfaces in the JDBC API are:
         • DriverManager class: Loads the driver for a database.
         • Driver interface: Represents a database driver. All JDBC driver classes
              must implement the Driver interface.
         • Connection interface: Enables you to establish a connection between a
              Java application and a database.
         • Statement interface: Enables you to execute SQL statements.
         • ResultSet interface: Represents the information retrieved from a
              database.
         • SQLException class: Provides information about the exceptions that
              occur while interacting with databases.


 ©NIIT                   JDBC and JavaBeans                 Lesson 1A / Slide 9 of 36
Introducing JDBC


Using JDBC API (Contd.)
    •    The steps to create JDBC application are:
         • Load a driver
         • Connect to a database
         • Create and execute JDBC statements
         • Handle SQL exceptions




 ©NIIT                   JDBC and JavaBeans          Lesson 1A / Slide 10 of 36
Introducing JDBC


Using JDBC API (Contd.)
    •    Loading a Driver


         •   Programmatically:
             • Using the forName() method
             • Using the registerDriver()method

         •   Manually:
             • By setting system property




 ©NIIT                      JDBC and JavaBeans    Lesson 1A / Slide 11 of 36
Introducing JDBC


Using JDBC API (Contd.)
    •    Using the forName() method
         • The forName() method is available in the java.lang.Class class.
         • The forName() method loads the JDBC driver and registers the driver
              with the driver manager.
         • The method call to use the the forName() method is:
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");




 ©NIIT                  JDBC and JavaBeans             Lesson 1A / Slide 12 of 36
Introducing JDBC


Using JDBC API (Contd.)
    •    Using the registerDriver()method
         • You can create an instance of the Driver class to load a JDBC driver.
         • This instance enables you to provide the name of the driver class at run
              time.
         • The statement to create an instance of the Driver class is:
              Driver d = new sun.jdbc.odbc.JdbcOdbcDriver();
         • You need to call the registerDriver() method to register the Driver
              object with the DriverManager.
         • The method call to register the JDBC-ODBC Bridge driver is:
              DriverManager.registerDriver(d);




 ©NIIT                   JDBC and JavaBeans              Lesson 1A / Slide 13 of 36
Introducing JDBC


Using JDBC API (Contd.)
    •    Setting System Property
         • Add the driver name to the jdbc.drivers system property to load a
              JDBC driver.
         • Use the –D command line option to set the system property on the
              command line.
         • The command to set the system property is:
              java –Djdbc.drivers=sun.jdbc.odbc.JdbcOdbcDriver
              SampleApplication




 ©NIIT                  JDBC and JavaBeans             Lesson 1A / Slide 14 of 36
Introducing JDBC


Using JDBC API (Contd.)
    •    Connecting to a Database
         • The DriverManager class provides the getConnection() method to
             create a Connection object.
         • The getConnection()method method has the following three forms:
             • Connection getConnection (String <url>)
             • Connection getConnection (String <url>, String
                  <username>, String <password>)
             • Connection getConnection (String <url>,Properties
                  <properties>)




 ©NIIT                 JDBC and JavaBeans            Lesson 1A / Slide 15 of 36
Introducing JDBC


Using JDBC API (Contd.)
    •    Creating and Executing JDBC Statements
         • The Connection object provides the createStatement() method to
              create a Statement object.
         • You can use static SQL statements to send requests to a database to
              retrieve results.
         • The Statement interface contains the following methods to send static
              SQL statements to a database:
              • ResultSet executeQuery(String str)
              • int executeUpdate(String str)
              • boolean execute(String str)




 ©NIIT                  JDBC and JavaBeans              Lesson 1A / Slide 16 of 36
Introducing JDBC


Using JDBC API (Contd.)
    •    Various database operations that you can perform using a Java application
         are:
          • Querying a table
          • Inserting rows in a table
          • Updating rows in a table
          • Deleting rows from a table
          • Creating a table
          • Altering and dropping a table




 ©NIIT                  JDBC and JavaBeans                Lesson 1A / Slide 17 of 36
Introducing JDBC


Using JDBC API (Contd.)
    •    Querying a Table
          • The SELECT statement is executed using the executeQuery() method and
             returns the output in the form of a ResultSet object.
          • The code snippet to retrieve data from the authors table is:
                String str = "SELECT * FROM authors";
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery(str);




 ©NIIT                   JDBC and JavaBeans             Lesson 1A / Slide 18 of 36
Introducing JDBC


Using JDBC API (Contd.)
    •    Inserting Rows in a Table
         • The executeUpdate() method enables you to add rows in a table.
         • The code snippet to insert a row in the authors table is:
              String str = "INSERT INTO authors (au_id, au_lname, au_fname,
              address, city, state, contract) VALUES ('998-72-3568',
              'Ringer','Albert','801 826-0752 67 Seventh Av.', 'Salt Lake
              City','UT','1')";
              Statement stmt = con.createStatement();
              int count = stmt.executeUpdate(str);




 ©NIIT                 JDBC and JavaBeans           Lesson 1A / Slide 19 of 36
Introducing JDBC


Using JDBC API (Contd.)
    •    Updating Rows in a Table
         • The code snippet to modify a row in the authors table is:
             String str = "UPDATE authors SET address='10932 Second Av.’
             WHERE au_id='998-72-3568'";
             Statement stmt = con.createStatement();
             int count = stmt.executeUpdate(str);


    •    Deleting Rows from a Table
         • The code snippet to delete a row from the authors table is:
              String str = "DELETE FROM authors WHERE au_id='998-72-3568'";
              Statement stmt = con.createStatement();
              int count = stmt.executeUpdate(str);




 ©NIIT                 JDBC and JavaBeans           Lesson 1A / Slide 20 of 36
Introducing JDBC


Using JDBC API (Contd.)
    •    Creating a Table
         • The CREATE TABLE statement is used to create and define the structure
              of a table in a database.
         • The code snippet to create a table is:
              String str="CREATE TABLE MyProduct"
              +" (p_id INTEGER,"
              +"p_name VARCHAR(25),"
              +"rate FLOAT,"
              +"unit_msr CHAR(6))";
              Statement stmt=con.createStatement();
              stmt.execute(str);




 ©NIIT                  JDBC and JavaBeans              Lesson 1A / Slide 21 of 36
Introducing JDBC


Using JDBC API (Contd.)
    •    Altering and Dropping a Table
         • DDL provides the ALTER statement to modify the definition of database
               object.
         • The code snippet to add a column to the MyProduct table is:
               String str="ALTER TABLE MyProduct "
               +"ADD quantity INTEGER";
               Statement stmt=con.createStatement();
               stmt.execute(str);
         • DDL provides the DROP TABLE statement to drop a table from a
               database.
         • The code snippet to drop the MyProduct table from a database is:
               String str="DROP TABLE MyProduct";
               Statement stmt=con.createStatement();
               stmt.execute(str);


 ©NIIT                  JDBC and JavaBeans              Lesson 1A / Slide 22 of 36
Introducing JDBC


Using JDBC API (Contd.)
    •    Handling SQL Exceptions
         • The java.sql package provides the SQLException class, which is
             derived from the java.lang.Exception class.
         • You can catch the SQLException in a Java application using the try and
             catch exception handling block.
         • The SQLException class contains various methods that provide error
             information, these methods are:
             • int getErrorCode(): Returns the error code associated with the
                   error occurred.
             • String getSQLState(): Returns X/Open error code.
             • SQLException getNextException(): Returns the next exception
                   in the chain of exceptions.




 ©NIIT                  JDBC and JavaBeans              Lesson 1A / Slide 23 of 36
Introducing JDBC


Accessing Result Sets
    •    A ResultSet object maintains a cursor that enables you to move through the
         rows stored in a ResultSet object.


    •    Types of Result Sets
         • The various types of ResultSet objects to store the output returned by
             a database are:
             • Read only: Allows you to only read the rows in a ResultSet object.
             • Forward only: Moves the result set cursor from first row to last row
                   in forward direction only.
             • Scrollable: Moves the result set cursor forward or backward
                   through the result set.
             • Updatable: Allows you to update the result set rows retrieved from
                   a database table.




 ©NIIT                   JDBC and JavaBeans              Lesson 1A / Slide 24 of 36
Introducing JDBC


Accessing Result Sets (Contd.)
    •      The following table lists various fields of ResultSet interface that you can
           use to specify the type of a ResultSet object:

         ResultSet Fields                                Description


 TYPE_SCROLL_SENTITIVE             Specifies that the cursor of the ResultSet object is
                                   scrollable and it reflects the changes in the data made
                                   by other users.

 TYPE_SCROLL_INSENSITIVE           Specifies that the cursor of the ResultSet object is
                                   scrollable and it does not reflect changes in the data
                                   made by other users.

 TYPE_FORWARD_ONLY                 Specifies that the cursor of the ResultSet object
                                   moves in forward direction only from the first row to
                                   the last row.

 ©NIIT                      JDBC and JavaBeans                 Lesson 1A / Slide 25 of 36
Introducing JDBC


Accessing Result Sets (Contd.)
    •     The following table lists various fields of the ResultSet interface that you
          can use to specify different concurrency modes of result sets:


                 ResultSet Fields                             Description



         CONCUR_READ_ONLY                        Specifies the concurrency mode that
                                                 does not allow you to update the
                                                 ResultSet object.

         CONCUR_UPDATABLE                        Specifies the concurrency mode that
                                                 allows you to update the ResultSet
                                                 object.



 ©NIIT                      JDBC and JavaBeans                Lesson 1A / Slide 26 of 36
Introducing JDBC


Accessing Result Sets (Contd.)
    •     The following table lists various fields of the ResultSet interface that you
          can use to specify different cursor states of result sets:


                 ResultSet Fields                             Description



         HOLD_CURSORS_OVER_COMMIT                Specifies that a ResultSet object
                                                 should not be closed after data is
                                                 committed to the database.

         CLOSE_CURSORS_AT_COMMIT                 Specifies that a ResultSet object
                                                 should be closed after data is
                                                 committed to the database.



 ©NIIT                     JDBC and JavaBeans                 Lesson 1A / Slide 27 of 36
Introducing JDBC


Accessing Result Sets (Contd.)
    •    The createStatement() method has the following three overloaded forms:

         •   Statement createStatement()
         •   Statement createStatement(int, int)
         •   Statement createStatement(int, int, int)




 ©NIIT                  JDBC and JavaBeans              Lesson 1A / Slide 28 of 36
Introducing JDBC


Accessing Result Sets (Contd.)
    •    The following tables lists the methods of ResultSet interface:

         Method                                       Description

boolean first()               Shifts the control of a result set cursor to the first row of
                              the result set.
boolean isFirst()             Determines whether the result set cursor points to the
                              first row of the result set.
boolean beforeFirst()         Shifts the control of a result set cursor before the first
                              row of the result set.
boolean isBeforeFirst()       Determines whether the result set cursor points before
                              the first row of the result set.
boolean last()                Shifts the control of a result set cursor to the last row of
                              the result set.
boolean isLast()              Determines whether the result set cursor points to the
                              last row of the result set.

 ©NIIT                   JDBC and JavaBeans                  Lesson 1A / Slide 29 of 36
Introducing JDBC


Accessing Result Sets (Contd.)
    •     The methods of ResultSet interface (Contd.)

         Method                                     Description
boolean afterLast()        Shifts the control of a result set cursor after the last row of
                           the result set.
boolean                    Determines whether the result set cursor points after the
isAfterLast()              last row of the result set.

boolean previous()         Shifts the control of a result set cursor to the previous row
                           of the result set.
boolean                    Shifts the control of a result set cursor to the row number
absolute(int i)            that you specify as a parameter.

boolean                    Shifts the control of a result set cursor, forward or
relative(int i)            backward, relative to the row number that you specify as a
                           parameter.

 ©NIIT                   JDBC and JavaBeans                   Lesson 1A / Slide 30 of 36
Introducing JDBC


Accessing Result Sets (Contd.)
    •    JDBC allows you to create an updatable result set that enables you to modify
         the rows in the result set.
    •    The following table lists some of the methods used with updatable result set:

         Method                                     Description

 void updateRow()             Updates a row of the current ResultSet object and the
                              underlying database table.
 void insertRow()             Inserts a row in the current ResultSet object and the
                              underlying database table.
 void deleteRow()             Deletes a row from the current ResultSet object and the
                              underlying database table.
 void updateString()          Updates the specified column with the given string value.

 void updateInt()             Updates the specified column with the given int value.

 ©NIIT                   JDBC and JavaBeans                Lesson 1A / Slide 31 of 36
Introducing JDBC


Demonstration-Creating a JDBC
  Application to Query a Database

    •    Problem Statement


         •   Create an application to retrieve information (author id, name,
             address, city, and state) about the authors who are living in the
             city where the city name begins with the letter “O”.




 ©NIIT                 JDBC and JavaBeans             Lesson 1A / Slide 32 of 36
Introducing JDBC


Demonstration-Creating a JDBC
  Application to Query a Database
  (Contd.)

    •    Solution


         •   JDBC-ODBC Bridge driver is to be used for creating the
             application. To solve the above problem, perform the following
             tasks:
             •   Create a Data Source Name (DSN).
             •   Code the application.
             •   Compile and execute the application.



 ©NIIT                 JDBC and JavaBeans            Lesson 1A / Slide 33 of 36
Introducing JDBC


Summary
In this lesson, you learned:


     •    JDBC Architecture consists of two layers:
          • JDBC application layer: Signifies a Java application that uses the JDBC
               API to interact with the JDBC driver manager.
          • JDBC driver layer: Contains a driver, such as an SQL Server driver,
               which enables a Java application to connect to a database. This layer
               acts as an interface between a Java application and a database.
     •    The JDBC driver manager manages various JDBC drivers.
     •    The JDBC driver is software that a Java application uses to access a
          database.




 ©NIIT                     JDBC and JavaBeans              Lesson 1A / Slide 34 of 36
Introducing JDBC


Summary (Contd.)
    •    JDBC supports four types of drivers:
         • JDBC-ODBC Bridge driver
         • Native-API Partly-Java driver
         • JDBC-Net Pure-Java driver
         • Native Protocol Pure-Java driver
    •    The JDBC API consists of various classes and interfaces that enable Java
         applications to interact with databases.
    •    The classes and interfaces of the JDBC API are defined in the java.sql and
         javax.sql packages.
    •    You can load a driver and register it with the driver manager either
         programmatically or manually.
    •    Two ways to load and register a driver programmatically are:
         • Using the Class.forName() method
         • Using the registerDriver() method

 ©NIIT                   JDBC and JavaBeans               Lesson 1A / Slide 35 of 36
Introducing JDBC


Summary (Contd.)
    •    You can add the driver name to the jdbc.drivers system property to load
         and register a JDBC driver manually.
    •    A Connection object establishes a connection between a Java application
         and a database.
    •    A Statement object sends requests to and retrieves results from a database.
    •    You can insert, update, and delete data from a table using the DML
         statements in Java applications.
    •    You can create, alter, and drop tables from a database using the DDL
         statements in Java applications.
    •    A ResultSet object stores the result retrieved from a database when a
         SELECT statement is executed.
    •    You can create various types of ResultSet objects such as read only,
         updatable, and forward only.




 ©NIIT                   JDBC and JavaBeans               Lesson 1A / Slide 36 of 36

Contenu connexe

Tendances (20)

Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Unit 04: From Requirements to the UX Model
Unit 04: From Requirements to the UX ModelUnit 04: From Requirements to the UX Model
Unit 04: From Requirements to the UX Model
 
3 f6 8_databases
3 f6 8_databases3 f6 8_databases
3 f6 8_databases
 
Unit03: Process and Business Models
Unit03: Process and Business ModelsUnit03: Process and Business Models
Unit03: Process and Business Models
 
01.egovFrame Training Book I
01.egovFrame Training Book I01.egovFrame Training Book I
01.egovFrame Training Book I
 
Unit 01 - Introduction
Unit 01 - IntroductionUnit 01 - Introduction
Unit 01 - Introduction
 
Java training noida hibernate+spring+struts+web services(1)
Java training noida hibernate+spring+struts+web services(1)Java training noida hibernate+spring+struts+web services(1)
Java training noida hibernate+spring+struts+web services(1)
 
3 f6 9_distributed_systems
3 f6 9_distributed_systems3 f6 9_distributed_systems
3 f6 9_distributed_systems
 
159747608 a-training-report-on
159747608 a-training-report-on159747608 a-training-report-on
159747608 a-training-report-on
 
Building Enterprise Application with J2EE
Building Enterprise Application with J2EEBuilding Enterprise Application with J2EE
Building Enterprise Application with J2EE
 
Introduction to Java EE (J2EE)
Introduction to Java EE (J2EE)Introduction to Java EE (J2EE)
Introduction to Java EE (J2EE)
 
Java J2EE
Java J2EEJava J2EE
Java J2EE
 
Part 2 java development
Part 2 java developmentPart 2 java development
Part 2 java development
 
Dependency Injection Styles
Dependency Injection StylesDependency Injection Styles
Dependency Injection Styles
 
VA Smalltalk Update
VA Smalltalk UpdateVA Smalltalk Update
VA Smalltalk Update
 
Aravind vinnakota ejb_architecture
Aravind vinnakota ejb_architectureAravind vinnakota ejb_architecture
Aravind vinnakota ejb_architecture
 
Subhadra Banerjee_latest
Subhadra Banerjee_latestSubhadra Banerjee_latest
Subhadra Banerjee_latest
 
Oracle
OracleOracle
Oracle
 

Similaire à JDBC Introduction Lesson (20)

Jdbc session01
Jdbc session01Jdbc session01
Jdbc session01
 
Java session16
Java session16Java session16
Java session16
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
10 J D B C
10  J D B C10  J D B C
10 J D B C
 
Jdbc
JdbcJdbc
Jdbc
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
Jdbc
JdbcJdbc
Jdbc
 
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
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Jdbc
JdbcJdbc
Jdbc
 
Assignment#10
Assignment#10Assignment#10
Assignment#10
 
Jdbc
JdbcJdbc
Jdbc
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part I
 
jdbc
jdbcjdbc
jdbc
 
JDBC
JDBCJDBC
JDBC
 
JDBC
JDBCJDBC
JDBC
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
 

Plus de Niit Care

Plus de Niit Care (19)

Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 
Dacj 1-3 b
Dacj 1-3 bDacj 1-3 b
Dacj 1-3 b
 
Dacj 1-3 a
Dacj 1-3 aDacj 1-3 a
Dacj 1-3 a
 
Dacj 1-2 c
Dacj 1-2 cDacj 1-2 c
Dacj 1-2 c
 
Dacj 1-2 a
Dacj 1-2 aDacj 1-2 a
Dacj 1-2 a
 
Dacj 1-1 c
Dacj 1-1 cDacj 1-1 c
Dacj 1-1 c
 
Dacj 1-1 b
Dacj 1-1 bDacj 1-1 b
Dacj 1-1 b
 
Dacj 1-1 a
Dacj 1-1 aDacj 1-1 a
Dacj 1-1 a
 
Dacj 2-2 b
Dacj 2-2 bDacj 2-2 b
Dacj 2-2 b
 
Dacj 2-2 a
Dacj 2-2 aDacj 2-2 a
Dacj 2-2 a
 
Dacj 2-1 c
Dacj 2-1 cDacj 2-1 c
Dacj 2-1 c
 
Dacj 2-1 b
Dacj 2-1 bDacj 2-1 b
Dacj 2-1 b
 

Dernier

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ 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
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Dernier (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ 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
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

JDBC Introduction Lesson

  • 1. Introducing JDBC Objectives In this lesson, you will learn about: • Layers in JDBC architecture • Types of JDBC drivers • Classes and interfaces of JDBC API • Steps to create JDBC applications ©NIIT JDBC and JavaBeans Lesson 1A / Slide 1 of 36
  • 2. Introducing JDBC Database Connectivity • Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases. • The following figure shows the Airline Reservation System developed in Java interacting with the Airlines database using the JDBC API: ©NIIT JDBC and JavaBeans Lesson 1A / Slide 2 of 36
  • 3. Introducing JDBC Database Connectivity (Contd.) • JDBC Architecture: • Provides the mechanism to translate Java statements into SQL statements. • Can be classified into two layers: • JDBC application layer • JDBC driver layer ©NIIT JDBC and JavaBeans Lesson 1A / Slide 3 of 36
  • 4. Introducing JDBC Database Connectivity (Contd.) • JDBC Drivers: • Convert SQL statements into a form that a particular database can interpret. • Retrieve the result of SQL statements and convert the result into equivalent JDBC API class objects. • Are of four types: • JDBC-ODBC Bridge driver • Native-API Partly-Java driver • JDBC-Net Pure-Java driver • Native Protocol Pure-Java driver ©NIIT JDBC and JavaBeans Lesson 1A / Slide 4 of 36
  • 5. Introducing JDBC Database Connectivity (Contd.) • JDBC-ODBC Bridge driver ©NIIT JDBC and JavaBeans Lesson 1A / Slide 5 of 36
  • 6. Introducing JDBC Database Connectivity (Contd.) • Native-API Partly-Java driver ©NIIT JDBC and JavaBeans Lesson 1A / Slide 6 of 36
  • 7. Introducing JDBC Database Connectivity (Contd.) • JDBC-Net Pure-Java driver ©NIIT JDBC and JavaBeans Lesson 1A / Slide 7 of 36
  • 8. Introducing JDBC Database Connectivity (Contd.) • Native-Protocol Pure-Java driver ©NIIT JDBC and JavaBeans Lesson 1A / Slide 8 of 36
  • 9. Introducing JDBC Using JDBC API • The JDBC API classes and interfaces are available in the java.sql and the javax.sql packages. • The commonly used classes and interfaces in the JDBC API are: • DriverManager class: Loads the driver for a database. • Driver interface: Represents a database driver. All JDBC driver classes must implement the Driver interface. • Connection interface: Enables you to establish a connection between a Java application and a database. • Statement interface: Enables you to execute SQL statements. • ResultSet interface: Represents the information retrieved from a database. • SQLException class: Provides information about the exceptions that occur while interacting with databases. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 9 of 36
  • 10. Introducing JDBC Using JDBC API (Contd.) • The steps to create JDBC application are: • Load a driver • Connect to a database • Create and execute JDBC statements • Handle SQL exceptions ©NIIT JDBC and JavaBeans Lesson 1A / Slide 10 of 36
  • 11. Introducing JDBC Using JDBC API (Contd.) • Loading a Driver • Programmatically: • Using the forName() method • Using the registerDriver()method • Manually: • By setting system property ©NIIT JDBC and JavaBeans Lesson 1A / Slide 11 of 36
  • 12. Introducing JDBC Using JDBC API (Contd.) • Using the forName() method • The forName() method is available in the java.lang.Class class. • The forName() method loads the JDBC driver and registers the driver with the driver manager. • The method call to use the the forName() method is: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); ©NIIT JDBC and JavaBeans Lesson 1A / Slide 12 of 36
  • 13. Introducing JDBC Using JDBC API (Contd.) • Using the registerDriver()method • You can create an instance of the Driver class to load a JDBC driver. • This instance enables you to provide the name of the driver class at run time. • The statement to create an instance of the Driver class is: Driver d = new sun.jdbc.odbc.JdbcOdbcDriver(); • You need to call the registerDriver() method to register the Driver object with the DriverManager. • The method call to register the JDBC-ODBC Bridge driver is: DriverManager.registerDriver(d); ©NIIT JDBC and JavaBeans Lesson 1A / Slide 13 of 36
  • 14. Introducing JDBC Using JDBC API (Contd.) • Setting System Property • Add the driver name to the jdbc.drivers system property to load a JDBC driver. • Use the –D command line option to set the system property on the command line. • The command to set the system property is: java –Djdbc.drivers=sun.jdbc.odbc.JdbcOdbcDriver SampleApplication ©NIIT JDBC and JavaBeans Lesson 1A / Slide 14 of 36
  • 15. Introducing JDBC Using JDBC API (Contd.) • Connecting to a Database • The DriverManager class provides the getConnection() method to create a Connection object. • The getConnection()method method has the following three forms: • Connection getConnection (String <url>) • Connection getConnection (String <url>, String <username>, String <password>) • Connection getConnection (String <url>,Properties <properties>) ©NIIT JDBC and JavaBeans Lesson 1A / Slide 15 of 36
  • 16. Introducing JDBC Using JDBC API (Contd.) • Creating and Executing JDBC Statements • The Connection object provides the createStatement() method to create a Statement object. • You can use static SQL statements to send requests to a database to retrieve results. • The Statement interface contains the following methods to send static SQL statements to a database: • ResultSet executeQuery(String str) • int executeUpdate(String str) • boolean execute(String str) ©NIIT JDBC and JavaBeans Lesson 1A / Slide 16 of 36
  • 17. Introducing JDBC Using JDBC API (Contd.) • Various database operations that you can perform using a Java application are: • Querying a table • Inserting rows in a table • Updating rows in a table • Deleting rows from a table • Creating a table • Altering and dropping a table ©NIIT JDBC and JavaBeans Lesson 1A / Slide 17 of 36
  • 18. Introducing JDBC Using JDBC API (Contd.) • Querying a Table • The SELECT statement is executed using the executeQuery() method and returns the output in the form of a ResultSet object. • The code snippet to retrieve data from the authors table is: String str = "SELECT * FROM authors"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(str); ©NIIT JDBC and JavaBeans Lesson 1A / Slide 18 of 36
  • 19. Introducing JDBC Using JDBC API (Contd.) • Inserting Rows in a Table • The executeUpdate() method enables you to add rows in a table. • The code snippet to insert a row in the authors table is: String str = "INSERT INTO authors (au_id, au_lname, au_fname, address, city, state, contract) VALUES ('998-72-3568', 'Ringer','Albert','801 826-0752 67 Seventh Av.', 'Salt Lake City','UT','1')"; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str); ©NIIT JDBC and JavaBeans Lesson 1A / Slide 19 of 36
  • 20. Introducing JDBC Using JDBC API (Contd.) • Updating Rows in a Table • The code snippet to modify a row in the authors table is: String str = "UPDATE authors SET address='10932 Second Av.’ WHERE au_id='998-72-3568'"; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str); • Deleting Rows from a Table • The code snippet to delete a row from the authors table is: String str = "DELETE FROM authors WHERE au_id='998-72-3568'"; Statement stmt = con.createStatement(); int count = stmt.executeUpdate(str); ©NIIT JDBC and JavaBeans Lesson 1A / Slide 20 of 36
  • 21. Introducing JDBC Using JDBC API (Contd.) • Creating a Table • The CREATE TABLE statement is used to create and define the structure of a table in a database. • The code snippet to create a table is: String str="CREATE TABLE MyProduct" +" (p_id INTEGER," +"p_name VARCHAR(25)," +"rate FLOAT," +"unit_msr CHAR(6))"; Statement stmt=con.createStatement(); stmt.execute(str); ©NIIT JDBC and JavaBeans Lesson 1A / Slide 21 of 36
  • 22. Introducing JDBC Using JDBC API (Contd.) • Altering and Dropping a Table • DDL provides the ALTER statement to modify the definition of database object. • The code snippet to add a column to the MyProduct table is: String str="ALTER TABLE MyProduct " +"ADD quantity INTEGER"; Statement stmt=con.createStatement(); stmt.execute(str); • DDL provides the DROP TABLE statement to drop a table from a database. • The code snippet to drop the MyProduct table from a database is: String str="DROP TABLE MyProduct"; Statement stmt=con.createStatement(); stmt.execute(str); ©NIIT JDBC and JavaBeans Lesson 1A / Slide 22 of 36
  • 23. Introducing JDBC Using JDBC API (Contd.) • Handling SQL Exceptions • The java.sql package provides the SQLException class, which is derived from the java.lang.Exception class. • You can catch the SQLException in a Java application using the try and catch exception handling block. • The SQLException class contains various methods that provide error information, these methods are: • int getErrorCode(): Returns the error code associated with the error occurred. • String getSQLState(): Returns X/Open error code. • SQLException getNextException(): Returns the next exception in the chain of exceptions. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 23 of 36
  • 24. Introducing JDBC Accessing Result Sets • A ResultSet object maintains a cursor that enables you to move through the rows stored in a ResultSet object. • Types of Result Sets • The various types of ResultSet objects to store the output returned by a database are: • Read only: Allows you to only read the rows in a ResultSet object. • Forward only: Moves the result set cursor from first row to last row in forward direction only. • Scrollable: Moves the result set cursor forward or backward through the result set. • Updatable: Allows you to update the result set rows retrieved from a database table. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 24 of 36
  • 25. Introducing JDBC Accessing Result Sets (Contd.) • The following table lists various fields of ResultSet interface that you can use to specify the type of a ResultSet object: ResultSet Fields Description TYPE_SCROLL_SENTITIVE Specifies that the cursor of the ResultSet object is scrollable and it reflects the changes in the data made by other users. TYPE_SCROLL_INSENSITIVE Specifies that the cursor of the ResultSet object is scrollable and it does not reflect changes in the data made by other users. TYPE_FORWARD_ONLY Specifies that the cursor of the ResultSet object moves in forward direction only from the first row to the last row. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 25 of 36
  • 26. Introducing JDBC Accessing Result Sets (Contd.) • The following table lists various fields of the ResultSet interface that you can use to specify different concurrency modes of result sets: ResultSet Fields Description CONCUR_READ_ONLY Specifies the concurrency mode that does not allow you to update the ResultSet object. CONCUR_UPDATABLE Specifies the concurrency mode that allows you to update the ResultSet object. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 26 of 36
  • 27. Introducing JDBC Accessing Result Sets (Contd.) • The following table lists various fields of the ResultSet interface that you can use to specify different cursor states of result sets: ResultSet Fields Description HOLD_CURSORS_OVER_COMMIT Specifies that a ResultSet object should not be closed after data is committed to the database. CLOSE_CURSORS_AT_COMMIT Specifies that a ResultSet object should be closed after data is committed to the database. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 27 of 36
  • 28. Introducing JDBC Accessing Result Sets (Contd.) • The createStatement() method has the following three overloaded forms: • Statement createStatement() • Statement createStatement(int, int) • Statement createStatement(int, int, int) ©NIIT JDBC and JavaBeans Lesson 1A / Slide 28 of 36
  • 29. Introducing JDBC Accessing Result Sets (Contd.) • The following tables lists the methods of ResultSet interface: Method Description boolean first() Shifts the control of a result set cursor to the first row of the result set. boolean isFirst() Determines whether the result set cursor points to the first row of the result set. boolean beforeFirst() Shifts the control of a result set cursor before the first row of the result set. boolean isBeforeFirst() Determines whether the result set cursor points before the first row of the result set. boolean last() Shifts the control of a result set cursor to the last row of the result set. boolean isLast() Determines whether the result set cursor points to the last row of the result set. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 29 of 36
  • 30. Introducing JDBC Accessing Result Sets (Contd.) • The methods of ResultSet interface (Contd.) Method Description boolean afterLast() Shifts the control of a result set cursor after the last row of the result set. boolean Determines whether the result set cursor points after the isAfterLast() last row of the result set. boolean previous() Shifts the control of a result set cursor to the previous row of the result set. boolean Shifts the control of a result set cursor to the row number absolute(int i) that you specify as a parameter. boolean Shifts the control of a result set cursor, forward or relative(int i) backward, relative to the row number that you specify as a parameter. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 30 of 36
  • 31. Introducing JDBC Accessing Result Sets (Contd.) • JDBC allows you to create an updatable result set that enables you to modify the rows in the result set. • The following table lists some of the methods used with updatable result set: Method Description void updateRow() Updates a row of the current ResultSet object and the underlying database table. void insertRow() Inserts a row in the current ResultSet object and the underlying database table. void deleteRow() Deletes a row from the current ResultSet object and the underlying database table. void updateString() Updates the specified column with the given string value. void updateInt() Updates the specified column with the given int value. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 31 of 36
  • 32. Introducing JDBC Demonstration-Creating a JDBC Application to Query a Database • Problem Statement • Create an application to retrieve information (author id, name, address, city, and state) about the authors who are living in the city where the city name begins with the letter “O”. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 32 of 36
  • 33. Introducing JDBC Demonstration-Creating a JDBC Application to Query a Database (Contd.) • Solution • JDBC-ODBC Bridge driver is to be used for creating the application. To solve the above problem, perform the following tasks: • Create a Data Source Name (DSN). • Code the application. • Compile and execute the application. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 33 of 36
  • 34. Introducing JDBC Summary In this lesson, you learned: • JDBC Architecture consists of two layers: • JDBC application layer: Signifies a Java application that uses the JDBC API to interact with the JDBC driver manager. • JDBC driver layer: Contains a driver, such as an SQL Server driver, which enables a Java application to connect to a database. This layer acts as an interface between a Java application and a database. • The JDBC driver manager manages various JDBC drivers. • The JDBC driver is software that a Java application uses to access a database. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 34 of 36
  • 35. Introducing JDBC Summary (Contd.) • JDBC supports four types of drivers: • JDBC-ODBC Bridge driver • Native-API Partly-Java driver • JDBC-Net Pure-Java driver • Native Protocol Pure-Java driver • The JDBC API consists of various classes and interfaces that enable Java applications to interact with databases. • The classes and interfaces of the JDBC API are defined in the java.sql and javax.sql packages. • You can load a driver and register it with the driver manager either programmatically or manually. • Two ways to load and register a driver programmatically are: • Using the Class.forName() method • Using the registerDriver() method ©NIIT JDBC and JavaBeans Lesson 1A / Slide 35 of 36
  • 36. Introducing JDBC Summary (Contd.) • You can add the driver name to the jdbc.drivers system property to load and register a JDBC driver manually. • A Connection object establishes a connection between a Java application and a database. • A Statement object sends requests to and retrieves results from a database. • You can insert, update, and delete data from a table using the DML statements in Java applications. • You can create, alter, and drop tables from a database using the DDL statements in Java applications. • A ResultSet object stores the result retrieved from a database when a SELECT statement is executed. • You can create various types of ResultSet objects such as read only, updatable, and forward only. ©NIIT JDBC and JavaBeans Lesson 1A / Slide 36 of 36