Sunteți pe pagina 1din 47

JDBC

1
Introduction
 Different database systems have their own API that
you must learn to write programs that interact with
the database

 Writing code capable of interfacing with databases


from more than one vendor was a great challenge.

 JDBC is Sun's attempt to create a platform-neutral


interface between databases and Java

2
JDBC Basics
 JDBC-Stands for Java Database Connectivity
 An API, or Application Programming Interface is a
set of classes, methods, and resources that
programs can use to do their work
 JDBC is a Java API for database connectivity, that
defines an interface for accessing various databases

 JDBC allows writing database applications in Java


without having any concern with the underlying
details of a particular database

3
JDBC Basics
 Nearly all relational database management systems
(RDBMSs) support SQL, and Java is platform
independent.

 Using JDBC you can send SQL, PL/SQL statements


to almost any relational database

 So JDBC makes it possible to write a single database


application that can run on different platforms and
interact with different DBMS

4
JDBC Basics
 In short JDBC helps the programmers to write java
applications that manage these three programming
activities:
 Connect to a data source, like a database.

 Send queries and update statements to the database.

 Retrieve and process the results received from the


database in answer to your query.

5
JDBC Architecture

6
JDBC Architecture
 The JDBC API uses a driver manager and database-specific
drivers to provide transparent connectivity to heterogeneous
databases

 The JDBC driver manager ensures that the correct driver is


used to access each data source

 It is capable of supporting multiple concurrent drivers


connected to multiple heterogeneous databases.

 A database vendor provides the JDBC driver which serves as


the interface to facilitate communications between JDBC and a
proprietary database.

 You need MySQL JDBC drivers to access the MySQL


database, and Oracle JDBC drivers to access the Oracle7
database.
Driver Manager:
 DriverManager is the very important part of the JDBC
architecture.

 The main responsibility of JDBC DriverManager is to load


all the drivers found in the system properly

 It then matches connection requests from the java


application with the proper database driver

 Internally, JDBC DriverManager is a class in JDBC API and


objects of this class can connect Java applications to a
JDBC driver

8
Driver:
 JDBC Drivers are written by vendors and must support the basic
features of the JDBC specification.

 It ensures that the application interacts with all databases in a


standard and uniform manner

 It receives the requests from the client, converts it into the


format understandable by the database and then presents it to
the database

 It receives the response, translates it back to Java data format


and presents it to the client application

 If the back-end database changes, only JDBC driver need to be


replaced.

9
JDBC Drivers
 JDBC drivers are client-side adapters (installed on the client
machine, not on the server) that convert requests from Java
programs to a protocol that the DBMS can understand.

Sun has divided the implementation types into four


categories:

 Type 1 - JDBC-ODBC Bridge Driver

 Type 2 - JDBC-Native Bridge Driver

 Type 3 - JDBC-Net Bridge Driver

 Type 4 - Direct JDBC Driver

10
Type 1 - JDBC-ODBC Bridge

11
Type 1 - JDBC-ODBC Bridge
 The JDBC-ODBC Bridge, is a database driver that
utilizes the ODBC driver to connect the database.

 This driver translates JDBC method calls into ODBC


function calls.

 The Bridge implements JDBC for any database for


which an ODBC driver is available

 The Bridge is always implemented as the


sun.jdbc.odbc Java package and it contains a native
library used to access ODBC.
12
Type 1 - JDBC-ODBC Bridge
 The driver is platform-dependent as it makes use of ODBC
which in turn depends on native libraries of the
operating system

 ODBC must be installed on the computer having the driver


and the database which is being connected to must
support an ODBC driver

 Performance overhead since the calls have to go through


the JDBC overhead bridge to the ODBC driver, then to the
native db connectivity interface.

 Since client-side software is needed it is not used for


web applications 13
Type 2 - JDBC-Native Bridge Driver

Type 2

14
Type 2 - JDBC-Native Bridge Driver
 This driver converts JDBC calls into database-specific
calls.

 This driver communicates directly with the database


server and requires some native code to connect to
the database.

 These drivers typically provided by the database


vendors and used in the same manner as the JDBC-
ODBC Bridge

15
Type 2 - JDBC-Native Bridge Driver
 Like Type 1 drivers, Type 2 drivers require native
database client libraries to be installed and configured
on the client machine.

 If we change the Database we have to change the


native API as it is specific to a database

 Better performance than Type 1 since no jdbc to odbc


translation is needed.

 Native API must be installed in the Client System and


hence type 2 drivers cannot be used for the Internet.
16
Type 3 - JDBC-Net Bridge

17
Type 3 - JDBC-Net Bridge
 It makes use of a middle-tier between the calling program
and the database

 The database requests are passed through the network to


the middleware-net-server which translates this request
into database commands for that database

 The connection occurs as follows:


Client -> JDBC Driver -> Middleware-Net Server ->
Any Database.

 Since the communication between client and the


middleware server is database independent, there is no
need for the vendor db library on the client machine 18
Type 3 - JDBC-Net Bridge
 This driver is very flexible allows access to multiple
databases using one driver.It depends on the number
of databases the middleware has been configured to
support.

 Can be used in internet since there is no client side


software needed.

 This driver is fully written in Java and hence Portable.

 Needs specific coding for different database at


middleware 19
Type 4 - Direct JDBC Driver

20
Type 4 - Direct JDBC Driver
 Type 4 drivers are pure Java drivers that converts
JDBC calls directly into the vendor-specific database
protocols

 Since there is direct communication with vendors data-base


no translation or middleware layers, are required, improving
performance.

 The type 4 driver is written completely in Java and is hence


platform independent

 Like Type 3 drivers, they do not require native database


libraries and can be deployed over the Internet without client
installation. 21
Type 4 - Direct JDBC Driver

 This is the highest performance driver available for the


database and is usually provided by the vendor itself.

 Only disadvantage: need to download a new driver for


each database engine

22
Which Driver should be used?

 If you are accessing one type of database, such as Oracle,


Sybase, or IBM, the preferred driver type is 4.

 If your Java application is accessing multiple types of


databases at the same time, type 3 is the preferred driver.

 Type 2 drivers are useful in situations where a type 3 or


type 4 driver is not available yet for your database.

 The type 1 driver is not considered a deployment-level


driver and is typically used for development and testing
purposes only.

23
Package java.sql :Classes
 It contains a set of interfaces and classes defined by JDBC
API that are used for communicating with the database

Important classes

DriverManager
The JDBC Driver Manager is a very important class that
defines objects which connect Java applications to a
JDBC driver

Its main responsibility is to load all the drivers found in the


system properly as well as to select the most appropriate
driver from opening a connection to a database. 24
Classes: java.sql

Date
The Date class is used to represent dates in the SQL
format YYYY-MM-DD

Contains methods to perform conversions of


java.util.Date and the SQL DATE type

• Time
The Time class is used to represent times in the SQL
format HH:MM:SS

Contains methods to perform SQL TIME type and Java


Time object conversions.
25
Classes: java.sql
TimeStamp

The Timestamp class is used to represent a combination


of date and time values in the ANSI SQL format YYYY-
MMDD HH:MM:SS.F

Types
provides definitions for all of the SQL data types that can
be supported by a JDBC driver

26
Interfaces in java.sql
Driver
All JDBC Drivers must implement the Driver interface.
Each driver should supply a class that implements
the Driver interface.

Connection
Represents a particular connection on which further
actions will be allowed

Statement
Used for executing SQL statements against the database
and retrieve data 27
Interfaces in java.sql
PreparedStatement
Creates a precompiled SQL statement and store it in the
database
Pre-compilation allows more faster & efficient statement

ResultSet
Represents the result of an SQL statement
Provides methods for navigating through the resulting
data

28
Interfaces in java.sql
CallableStatement
Used for executing stored procedures

ResultSetMetaData
Gives information like type and properties of the columns in a
result set

DatabaseMetaData
Provides information about the database as a whole

29
Using JDBC
 Seven steps in using JDBC to access a database:
1. Importing java.sql package
2. Load the driver (Only performed once)
3. Establishing a Connection to the database (Save for later
use)
4. Obtain a Statement object from the Connection
5. Use the Statement object to execute SQL. [Updates, inserts
and deletes return Boolean. Selects return a ResultSet]
6. Retrieve and Navigate through ResultSet, using data as
required
7. Close Statement and connection

30
Using JDBC

31
Loading a driver

The JDBC driver must be loaded before connect to the DBMS.

The driver is loaded by calling the Class.forName() method and


passing it the name of the driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

32
Connecting to the DBMS
Once the driver is loaded, connect to the DBMS using method
DriverManager.getConnection()

To connect to a JDBC data source, its name must be represented


as a URL of the following format:
jdbc:<subprotocol>:<subname>

 All JDBC URLs start with jdbc. The subprotocol is actually


determined by the driver you are using
 The subname can contain additional information used by the
satisfying subprotocol (i.e. driver), such as the location of the
data source, as well as a port number

.
33
Connecting to the DBMS
 The DriverManager.getConnection() method is passed the
URL of the database, and the userID and password if
required by the DBMS
 Eg:
String url =“jdbc:odbc:CustomerInformation”;
String userID=“sjec”;
String password = “comp”
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDrive”);
Connection conn =
DriverManager.getConnection(url,userID,password);
}
 This method returns a Connection interface that is used
throughout the process to reference the database.
34
Creating and executing a statement.
 Statement object is used to send queries and commands to the
database and is created from the Connection as follows:

Statement statement = conn.createStatement();

 The Statement object is used to send SQL queries by using the


executeQuery method, which returns a ResultSet object,that
contains the response from the DBMS

Eg: String query = "SELECT col1, col2, col3 FROM sometable”;


ResultSet resultSet = statement.executeQuery(query);

35
Creating and executing a statement.
 Statement object is used to send queries and commands to the
database and is created from the Connection as follows:

Statement statement = conn.createStatement();

 The Statement object is used to send SQL queries by using the


executeQuery method, which returns a ResultSet object,that
contains the response from the DBMS

Eg: String query = "SELECT col1, col2, col3 FROM sometable”;


ResultSet resultSet = statement.executeQuery(query);

 To modify the database, use executeUpdate instead of


executeQuery, and supply a string that uses UPDATE, INSERT, or
DELETE. 36
Processing data returned by the DBMS
 A ResultSet provides access to a table of data generated by
executing a Statement.
 The table rows are retrieved in sequence.
 A ResultSet maintains a cursor pointing to its current row of data
.
 The methods of the ResultSet interface can be broken down into
three categories:

 Navigational methods used to move the cursor around.


 Get methods that are used to view the data in the columns
of the current row being pointed to by the cursor.
 Update methods that update the data in the columns of the
current row.

37
ResultSet:Navigational Methods
 boolean next()-Moves the cursor to the next row

 int getRow()-Returns the row number that the cursor is


pointing

 boolean relative(int row)-Moves the cursor the given


number of rows forward or backwards from where it
currently is pointing

 boolean absolute(int row)-Moves the cursor to the


specified row.

38
ResultSet: Get Methods
 The ResultSet interface contains dozens of methods for
getting the data of the current row.

 There is a get method for each of the possible data types,


and each get method has two versions:

 one that takes in a column name


 one that takes in a column index.

 public int getInt(String columnName): Returns the int in the


current row in the column named columnName

 public int getInt(int columnIndex): Returns the int in the 39


current row in the specified column index
ResultSet: Get Methods
 The ResultSet interface contains a collection of update
methods for updating the data of a result set

 there are two update methods for each data type:

 one that takes in a column name


 one that takes in a column index.

 public void updateString(int columnIndex, String s):


Changes the String in the specified column to the value of s.

 public void updateString(String columnName, String s):


Changes the String in the specified column to the value of s
40
Using a ResultSet
String queryCS4400 = “select * from CS4400”;
ResultSet rs = Stmt.executeQuery(queryCS4400);
While (rs.next())
{
int ssn = rs.getInt(“SSN”);
` String name = rs.getString(“NAME”);
int marks = rs.getInt(“MARKS”);
}

41
Prepared Statement
 A prepared statement is an SQL statement that contains
parameters.

 When the Prepared- Statement object is created, this statement


is sent to the database and precompiled.

 These statements can be efficiently executed multiple times with


just a change in a parameter value. ie, the SQL statement does
not have to be parsed and compiled each time.

 java.sql.PreparedStatement interface is used to represent a


prepared SQL statement

 Before a prepared statement can be executed, each parameter


needs to be assigned using one of the set methods 42
Prepared Statement
Using a prepared statement involves the following steps:
1. Create a PreparedStatement object using one of the
prepareStatement() methods of the connection.

2. Use the appropriate set methods of the PreparedStatement


interface to set each of the parameters of the prepared statement.

3. Invoke one of the execute() methods of the PreparedStatement


to execute the statement.

Eg: String insert = “Insert into CS4400 (?,?,?)”;


PreparedStatement stmt2 = con.prepareStatement(insert);
stmt2.setInt(1,123456789);
stmt2.setString(2,abc);
stmt2.setInt(3,100);
stmt2.executeUpdate(); 43
Callable Statement

 Used for executing stored procedures


CallableStatement cs = conn.prepareCall("{call StoreProcedureNa
me}");
ResultSet rs = cs.executeQuery();

eg: CallableStatement cs1 = con.prepareCall("{call


HelloWorld}");
ResultSet rs1 = cs1.executeQuery();

44
Java Example
 import java.sql.*

 public class JDBCSample {

 public static void main( String args[]) {

 String userName = "testuser";
 String password = "testpass";
 String url = "jdbc:mysql://localhost/test";
 try {
 Class.forName ("com.mysql.jdbc.Driver");
 Connection con = DriverManager.getConnection (url, userName,
password);

45
 //Create a Statement class to execute the SQL statement
 Statement stmt = con.createStatement();

 //Execute the SQL statement and get the results in a
Resultset
 ResultSet rs = stmd.executeQuery("select moviename,
releasedate from movies");

 // Iterate through the ResultSet, displaying two values
 // for each row using the getString method

 while (rs.next())
 System.out.println("Name= " + rs.getString("moviename") +
" Date= " + rs.getString("releasedate");
 }

46
 catch (SQLException e) {
 e.printStackTrace();
 }
 catch (Exception e) {
 e.printStackTrace();
 }
 finally {
 // Close the connection
 con.close();
 }
 }
 }

S-ar putea să vă placă și