SlideShare une entreprise Scribd logo
1  sur  18
JDBC
(Java Database Connectivity)
Contents
 Overview
   JDBC Model
   JDBC Driver Type
 JDBC Programming Steps
     Step 1 : Loading a JDBC Driver
     Step 2 : Connecting to a Database
     Step 3 : Executing SQL
     Step 4 : Processing the Results
     Step 5 : Closing Database Connection
 The PreparedStatement Object
 Summary
Overview
 JDBC
   JDBC is a standard interface for connecting to relational
    databases from Java, was developed by JavSoft.
   The JDBC Classes and Interfaces are in the java.sql
    package
   JDBC is Java API for executing SQL statements
     Provides a standard API for tool/database developers
     Possible to write database applications using a pure
      Java API
     Easy to send SQL statements to virtually any relational
      database
 What does JDBC do?
   Establish a connection with a database
   Send SQL statements                     Database
         JAVA Applet/ JDBC Call             Command
   Process the results
         Application            JDBC Driver          Database
Overview
 Reason for JDBC
   Database vendors (Microsoft Access, Oracle
   etc.) provide proprietary (non standard) API
   for sending SQL to the server and receiving
   results from it
  Languages such as C/C++ can make use of
   these proprietary APIs directly
    High performance
    Can make use of non standard features of
     the database
    All the database code needs to be rewritten
     if you change database vendor or product
  JDBC is a vendor independent API for
   accessing relational data from different
   database vendors in a consistent way
JDBC Driver Type
  Drive types are used to categorize the technology used to
  connect to the database.

 JDBC-ODBC bridge plus ODBC driver (Type 1)
 Native-API partly-Java driver (Type 2)
 JDBC-Net pure Java driver (Type 3)
 Native Protocol pure Java API driver (Type 4)
JDBC Programming Steps
                       1) Register the driver
     Connect           2) Create a connection to the database



                       1) Create a statement
     Query             2) Query the database



                       1) Get a result set
     Process Results   2) Assign results to Java variables



                       1) Close the result set
     Close             2) Close the statement
                       3) Close the connection
Skeleton Code
Class.forName(DRIVERNAME);                             Loading a JDBC driver

Connection con = DriverManager.getConnection(CONNECTIONURL,DBID,DBPASSWORD);

Statement stmt = con.createStatement();                       Connecting to a database
ResultSet rs = stmt.executeQuery(“SELECT a, b, c FROM member);

While(rs.next())
{                                                   Executing SQL
  Int x = rs.getInt(“a”);
  String s = rs.getString(“b”);
  Float f = rs.getFloat(“c”);                     Processing the result set
}

rs.close();
stmt.close();
                                  Closing the connections
con.close();
Step 1 : Loading a JDBC Driver
 A JDBC driver is needed to connect to a database
 Loading a driver requires the class name of the driver.
  Ex) JDBC-ODBC: sun.jdbc.odbc.JdbcOdbcDriver
      Oracle driver: oracle.jdbc.driver.OracleDriver
      MySQL: com.mysql.jdbc.Driver


 Loading the driver class


        Class.forName("com.mysql.jdbc.Driver");

 It is possible to load several drivers.
 The class DriverManager manages the loaded driver(s)
Step 2 : Connecting to a Database
 JDBC URL for a database
  Identifies the database to be connected
  Consists of three-part:
                 jdbc:<subprotocol>:<subname>

    Protocol: JDBC is
     Protocol: JDBC is      Sub-protocol:
                             Sub-protocol:   Subname: indicates the location and
                                             Subname: indicates the location and
    the only protocol in
     the only protocol in   identifies a
                             identifies a    name of the database to be
                                             name of the database to be
    JDBC
     JDBC                   database
                             database        accessed. Syntax is driver specific
                                             accessed. Syntax is driver specific
                            driver
                             driver

            Ex) jdbc:mysql://oopsla.snu.ac.kr/mydb
Step 2 : Connecting to a Database
   The DriverManager allows you to connect to a database
    using the specified JDBC driver, database location,
    database name, username and password.
   It returns a Connection object which can then be used to
    communicate with the database.
Connection connection =
DriverManager.getConnection("jdbc:mysql://oopsla.snu.ac.kr/mydb",“userid",“password");

                JDBC URL
                JDBC URL
                Vendor of database, Location of
                Vendor of database, Location of   Username
                                                  Username               Password
                                                                         Password
                database server and name of
                database server and name of
                database
                database
Step 3 : Executing SQL
 Statement object
   Can be obtained from a Connection object

           Statement statement =
  
           connection.createStatement();
      Sends SQL to the database to be executed
 Statement has three methods to execute a SQL statement:
   executeQuery() for QUERY statements
       Returns a ResultSet which contains the query results
   executeUpdate() for INSERT, UPDATE, DELETE, or DDL
      statements
       Returns an integer, the number of affected rows from the SQL
   execute() for either type of statement
Step 3 : Executing SQL
 Execute a select statement
   Statement stmt = conn.createStatement();
   ResultSet rset = stmt.executeQuery
    ("select RENTAL_ID, STATUS from ACME_RENTALS");



 Execute a delete statement
   Statement stmt = conn.createStatement();
   int rowcount = stmt.executeUpdate
                    ("delete from ACME_RENTAL_ITEMS
                    where rental_id = 1011");
Step 4 : Processing the Results
 JDBC returns the results of a query in a ResultSet object
   ResultSet object contains all of the rows which satisfied the
    conditions in an SQL statement
 A ResultSet object maintains a cursor pointing to its
  current row of data
   Use next() to step through the result set row by row
     next() returns TRUE if there are still remaining records
   getString(), getInt(), and getXXX() assign each value to a Java
    variable
        Internal Pointer            ResultSet



               Record 1       Record 2          Record 3          Record 4



        The internal pointer starts one before the first record
Step 4 : Processing the Results
 Example
   Statement stmt = con.createStatement();
   ResultSet rs = stmt.executeQuery(“SELECT ID, name, score FROM table1”);
                                  NOTE
                                  You must step the cursor to the first record before read the results
   While (rs.next()){
                                           This code will not skip the first record
         int id = rs.getInt(“ID”);
         String name = rs.getString(“name”);
         float score = rs.getFloat(“score”);
         System.out.println(“ID=” + id + “ ” + name + “ ” + score);}


                ID      name      score                          Output
                1        James     90.5                          ID=1 James 90.5
                2        Smith     45.7                          ID=2 Smith 45.7
                3       Donald     80.2                          ID=3 Donald 80.2
                     Table1
Step 5 : Closing Database Connection
 It is a good idea to close the Statement and Connection
  objects when you have finished with them
 Close the ResultSet object
        rs.close();
 Close the Statement object
        stmt.close();
 Close the connection
        connection.close();
The PreparedStatement Object
 A PreparedStatement object holds precompiled SQL
   statements
  Use this object for statements you want to execute more
   than once
  A PreparedStatement can contain variables (?) that you
// Create the prepared statement the statement
   supply each time you execute
PreparedStatement pstmt = con.prepareStatement(“UPDATE
table1 SET status = ? WHERE id =?”)
// Supply values for the variables
pstmt.setString (1, “out”);
pstmt.setInt(2, id);
// Execute the statement
pstmt.executeUpdate();
Summary
 JDBC
  Standard interface for connecting to relational
   databases from Java
  Vendor independent API for accessing
   relational data
  JDBC has four driver type
   JDBC-ODBC bridge plus ODBC driver
   Native-API partly-Java driver
   JDBC-Net pure Java driver
   Native Protocol pure Java API driver

Contenu connexe

Tendances (20)

Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05
 
Jdbc
JdbcJdbc
Jdbc
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
 
DataBase Connectivity
DataBase ConnectivityDataBase Connectivity
DataBase Connectivity
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Jdbc
Jdbc   Jdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
 
Jdbc
JdbcJdbc
Jdbc
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 

En vedette (11)

Pseudo CSS Selectors
Pseudo CSS SelectorsPseudo CSS Selectors
Pseudo CSS Selectors
 
CSS Pseudo Classes
CSS Pseudo ClassesCSS Pseudo Classes
CSS Pseudo Classes
 
Css selectors
Css selectorsCss selectors
Css selectors
 
Css pseudo-classes
Css pseudo-classesCss pseudo-classes
Css pseudo-classes
 
Casc Style Sheets Ii
Casc Style Sheets IiCasc Style Sheets Ii
Casc Style Sheets Ii
 
Week 12 CSS - Review from last week
Week 12 CSS - Review from last weekWeek 12 CSS - Review from last week
Week 12 CSS - Review from last week
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
Introduction to CSS
Introduction to CSSIntroduction to CSS
Introduction to CSS
 
Agile Development | Agile Process Models
Agile Development | Agile Process ModelsAgile Development | Agile Process Models
Agile Development | Agile Process Models
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 

Similaire à JDBC (20)

Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
Lecture17
Lecture17Lecture17
Lecture17
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
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
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
JDBC
JDBCJDBC
JDBC
 

JDBC

  • 2. Contents  Overview  JDBC Model  JDBC Driver Type  JDBC Programming Steps  Step 1 : Loading a JDBC Driver  Step 2 : Connecting to a Database  Step 3 : Executing SQL  Step 4 : Processing the Results  Step 5 : Closing Database Connection  The PreparedStatement Object  Summary
  • 3. Overview  JDBC  JDBC is a standard interface for connecting to relational databases from Java, was developed by JavSoft.  The JDBC Classes and Interfaces are in the java.sql package  JDBC is Java API for executing SQL statements  Provides a standard API for tool/database developers  Possible to write database applications using a pure Java API  Easy to send SQL statements to virtually any relational database  What does JDBC do?  Establish a connection with a database  Send SQL statements Database JAVA Applet/ JDBC Call Command  Process the results Application JDBC Driver Database
  • 4. Overview  Reason for JDBC  Database vendors (Microsoft Access, Oracle etc.) provide proprietary (non standard) API for sending SQL to the server and receiving results from it  Languages such as C/C++ can make use of these proprietary APIs directly  High performance  Can make use of non standard features of the database  All the database code needs to be rewritten if you change database vendor or product  JDBC is a vendor independent API for accessing relational data from different database vendors in a consistent way
  • 5. JDBC Driver Type Drive types are used to categorize the technology used to connect to the database.  JDBC-ODBC bridge plus ODBC driver (Type 1)  Native-API partly-Java driver (Type 2)  JDBC-Net pure Java driver (Type 3)  Native Protocol pure Java API driver (Type 4)
  • 6.
  • 7. JDBC Programming Steps 1) Register the driver Connect 2) Create a connection to the database 1) Create a statement Query 2) Query the database 1) Get a result set Process Results 2) Assign results to Java variables 1) Close the result set Close 2) Close the statement 3) Close the connection
  • 8. Skeleton Code Class.forName(DRIVERNAME); Loading a JDBC driver Connection con = DriverManager.getConnection(CONNECTIONURL,DBID,DBPASSWORD); Statement stmt = con.createStatement(); Connecting to a database ResultSet rs = stmt.executeQuery(“SELECT a, b, c FROM member); While(rs.next()) { Executing SQL Int x = rs.getInt(“a”); String s = rs.getString(“b”); Float f = rs.getFloat(“c”); Processing the result set } rs.close(); stmt.close(); Closing the connections con.close();
  • 9. Step 1 : Loading a JDBC Driver  A JDBC driver is needed to connect to a database  Loading a driver requires the class name of the driver. Ex) JDBC-ODBC: sun.jdbc.odbc.JdbcOdbcDriver Oracle driver: oracle.jdbc.driver.OracleDriver MySQL: com.mysql.jdbc.Driver  Loading the driver class Class.forName("com.mysql.jdbc.Driver");  It is possible to load several drivers.  The class DriverManager manages the loaded driver(s)
  • 10. Step 2 : Connecting to a Database  JDBC URL for a database  Identifies the database to be connected  Consists of three-part: jdbc:<subprotocol>:<subname> Protocol: JDBC is Protocol: JDBC is Sub-protocol: Sub-protocol: Subname: indicates the location and Subname: indicates the location and the only protocol in the only protocol in identifies a identifies a name of the database to be name of the database to be JDBC JDBC database database accessed. Syntax is driver specific accessed. Syntax is driver specific driver driver Ex) jdbc:mysql://oopsla.snu.ac.kr/mydb
  • 11. Step 2 : Connecting to a Database  The DriverManager allows you to connect to a database using the specified JDBC driver, database location, database name, username and password.  It returns a Connection object which can then be used to communicate with the database. Connection connection = DriverManager.getConnection("jdbc:mysql://oopsla.snu.ac.kr/mydb",“userid",“password"); JDBC URL JDBC URL Vendor of database, Location of Vendor of database, Location of Username Username Password Password database server and name of database server and name of database database
  • 12. Step 3 : Executing SQL  Statement object  Can be obtained from a Connection object Statement statement =  connection.createStatement(); Sends SQL to the database to be executed  Statement has three methods to execute a SQL statement:  executeQuery() for QUERY statements  Returns a ResultSet which contains the query results  executeUpdate() for INSERT, UPDATE, DELETE, or DDL statements  Returns an integer, the number of affected rows from the SQL  execute() for either type of statement
  • 13. Step 3 : Executing SQL  Execute a select statement Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery ("select RENTAL_ID, STATUS from ACME_RENTALS");  Execute a delete statement Statement stmt = conn.createStatement(); int rowcount = stmt.executeUpdate ("delete from ACME_RENTAL_ITEMS where rental_id = 1011");
  • 14. Step 4 : Processing the Results  JDBC returns the results of a query in a ResultSet object  ResultSet object contains all of the rows which satisfied the conditions in an SQL statement  A ResultSet object maintains a cursor pointing to its current row of data  Use next() to step through the result set row by row  next() returns TRUE if there are still remaining records  getString(), getInt(), and getXXX() assign each value to a Java variable Internal Pointer ResultSet Record 1 Record 2 Record 3 Record 4 The internal pointer starts one before the first record
  • 15. Step 4 : Processing the Results  Example Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(“SELECT ID, name, score FROM table1”); NOTE You must step the cursor to the first record before read the results While (rs.next()){ This code will not skip the first record int id = rs.getInt(“ID”); String name = rs.getString(“name”); float score = rs.getFloat(“score”); System.out.println(“ID=” + id + “ ” + name + “ ” + score);} ID name score Output 1 James 90.5 ID=1 James 90.5 2 Smith 45.7 ID=2 Smith 45.7 3 Donald 80.2 ID=3 Donald 80.2 Table1
  • 16. Step 5 : Closing Database Connection  It is a good idea to close the Statement and Connection objects when you have finished with them  Close the ResultSet object rs.close();  Close the Statement object stmt.close();  Close the connection connection.close();
  • 17. The PreparedStatement Object  A PreparedStatement object holds precompiled SQL statements  Use this object for statements you want to execute more than once  A PreparedStatement can contain variables (?) that you // Create the prepared statement the statement supply each time you execute PreparedStatement pstmt = con.prepareStatement(“UPDATE table1 SET status = ? WHERE id =?”) // Supply values for the variables pstmt.setString (1, “out”); pstmt.setInt(2, id); // Execute the statement pstmt.executeUpdate();
  • 18. Summary  JDBC  Standard interface for connecting to relational databases from Java  Vendor independent API for accessing relational data  JDBC has four driver type  JDBC-ODBC bridge plus ODBC driver  Native-API partly-Java driver  JDBC-Net pure Java driver  Native Protocol pure Java API driver