Vous êtes sur la page 1sur 15

Chapter 1: JDBC

Introduction:
JDBC stands for Java Database Connectivity. Java Database Connectivity (JDBC) is an
application programming interface (API) which allows the programmer to connect and interact
with databases. JDBC helps you to write Java applications that manage these three programming
activities:

1. Connect to a data source, like a database

2. Send queries and update statements to the database

3. Retrieve and process the results received from the database in answer to your query

Programs developed using Java & JDBC API are platform & vendor independent. JDBC API is
implemented in java.sql package.

1.1 The design of JDBC

JJDBC consists of two layers: the JDBC API and the JDBC Driver Manager API.

The JDBC API is the top layer which gives programmatic access to relational data from Java.
Using the JDBC API, applications can execute SQL statements, retrieve results, and propagate
changes back to an underlying data source. The JDBC API can also interact with multiple data
sources in a distributed, heterogeneous environment. The JDBC API is part of the Java platform;
it includes the Java Standard Edition (Java SE) and Java Enterprise Edition (JEE). The JDBC 4.0
API is divided into two packages: java.sql and javax.sql. Both packages are included in the Java
SE and Java EE platforms

The JDBC API communicates with the JDBC Driver Manager API, sending it various SQL
statements. The manager communicates (transparent to the programmer) with the various third
party drivers (provided by Database vendors like Oracle) that actually connect to the database
and return the information from the query.
1.2 Basic JDBC program Concept

The basic JDBC program follows the following steps:


1. Establish a connection
2. Create JDBC Statements
3. Execute SQL Statements
4. Display Result
5. Close connections

1 Load the vendor specific driver: We can load the driver by using Class.forName() method.
// Using Type-1 Driver
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);

2 Establish a connection to database: The DriverManager class defines the objects which
connect Java applications to a JDBC driver. The task of the DriverManager class is to keep
track of the drivers that are available and handles establishing a connection between a
database and the appropriate driver.

String url=jdbc:odbc:myDSN;
Connection con =null;
con= DriverManager.getConnection(url,dbUser,dbPassword);

3 Create JDBC Statements and execute the SQL query: SQL query can be executed on the
database using any of the 3 statements in Java viz. Statement, PreparedStatement or
CallableStatement. CallableStatement is used for calling stored procedures where as
PreparedStatement is used for executing parameterized queries.

String sql=SELECT Eno, Ename, Salary FROM Employee;


Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
4 Fetch & display the results: The ResultSet object is used to access a table of data that was
generated by running a query. The table rows are retrieved in sequence. Within a row, column
values can be accessed in any order. The data stored in ResultSet is retrieved by using the
various get methods, depending on the type of data being retrieved. The next() method is
used to move to the next row.
5 Close the connection: It is important to close the connection as well as statements objects to
ensure changes made to the database.
con.close();

import java.sql.*; //needed for JDBC


import java.io.*;

class MakeDB
{
public static void main (String args[])
{
try
{
//Step 1: load the driver needed by the application
Class.forName("specialdb.Driver");

//Step 2: Establish connection


String dbaseURL = " jdbc:odbc:myDSN ";
Connection con = DriverManager.getConnection(dbaseURL,"dbUser",
"dbPassword");

//Create a statement and execute the SQL query


Statement query = dbConnection.getStatement();
ResultSet rs = query.executeQuery("SELECT * from Employee);

//Iterate through the results and print them to standard output


while(rs.next())
{
String fname = results.getString("first_name);
String lname = results.getString("last_name");
System.out.println("Found user " + fname + " " + lname);
}
}
catch (SQLException e){
System.out.println("SQLException: " + e.);
}
catch(ClassNotFoundException e) {
System.out.println("ClassNotFoundException: " + e);
}
}
}

1.3 Drivers
JDBC drivers implement the defined interfaces in the JDBC API for interacting with your
database server. For example, using JDBC drivers enable you to open database connections and
to interact with it by sending SQL or database commands then receiving results with Java. The
Java.sql package that ships with JDK contains various classes with their behaviors defined and
their actual implementations are done in third-party drivers. Third party vendors implement the
java.sql Driver interface in their database driver.

Types of Drivers:

JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which are explained below:
Type 1: JDBC-ODBC Bridge Driver:
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC requires configuring on your system a Data Source Name (DSN) that
represents the target database.
The driver converts JDBC method calls into ODBC function calls. The driver is platform-
dependent as it makes use of ODBC which in turn depends on native libraries of the underlying
operating system.
When Java first came out, this was a useful driver because most databases only supported ODBC
access but now this type of driver is recommended only for experimental use or when no other
alternative is available.

The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of driver.
Advantages
o Easy to use.
o Can be easily connected to almost any database, for which ODBC driver is installed.
Disadvantages
o Performance overhead since the calls have to go through the JDBC overhead bridge
to the ODBC driver, then to the native database connectivity interface.
o The ODBC driver needs to be installed on the client machine
o Since the driver is not written fully in Java, Type 1 drivers are not portable.

Type 2: JDBC-Native API:


In a Type 2 driver, JDBC API calls are converted into native API calls which are unique to the
database. It converts the JDBC calls into a database specific call for databases such as SQL,
ORACLE etc. This driver communicates directly with the database server. These drivers are
typically provided by the database vendors and are used in the same manner as the JDBC-ODBC
Bridge; the vendor-specific driver must be installed on each client machine.
Advantages:
Better performance than Type 1; speed increases with a Type 2 driver, because it
eliminates ODBC's overhead.

Disadvantages
The vendor client library needs to be installed on the client machine.
Cannot be used in internet due the client side software needed.
Not all databases give the client side library.
It is platform dependent.

Type 3: JDBC-Net pure Java/ Network Protocol Driver:

In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's configuration
in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 drivers to communicate with the database.

Advantages
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. Also the
client to middleware neednt be changed for a new database.
The Middleware Server can provide typical middleware services like caching, load
balancing, logging, auditing etc.
Can be used in internet since there is no client side software needed.
At client side a single driver can handle any database.
Disadvantages:
Requires database-specific coding to be done in the middle tier.
An extra layer added may result in a time-bottleneck. But typically this is overcome by
providing efficient middleware services.

Type 4: 100% pure Java:

A Type 4 driver, a pure Java-based driver, communicates directly with vendor's database through
socket connection. This is the highest performance driver available for the database and is
usually provided by the vendor itself.
This kind of driver is extremely flexible; you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.
Advantages:
Platform independent
No intermediate format is required; application connects directly to the database
server; performance will be fast.
JVM manages all aspects
Disadvantages:
At client side, a separate driver is needed for each database.
Summary:
If you are accessing one type of database such as Oracle, SQL Server, MySQL etc.
then the preferred driver type is Type 4.
If your Java application is accessing multiple types of databases at 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.
The Type 1 driver is not considered a deployment-level driver and is typically used
for development and testing purposes only.

1.4 Architecture of JDBC

The JDBC API supports both two-tier and three-tier processing models for database access but in
general, JDBC Architecture consists of two layers
JDBC API: This provides the application-to-JDBC Manager connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

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. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases. Following is the architectural diagram, which shows the location of the
driver manager with respect to the JDBC drivers and the Java application
1.5 Making the Connection, Statement , ResultSet , PreparedStatement,
CallableStatement

We can establish a connection using the DriverManager.getConnection() method. Let me list


the three overloaded DriverManager.getConnection() methods

getConnection(String url)

getConnection(String url, Properties prop)

getConnection(String url, String user, String password)

Here each form requires a database URL. A database URL is an address that points to your
database. The most commonly used form of getConnection() requires you to pass a
database URL, a username, and a password.

At the end of your JDBC program, it is required explicitly to close all the connections to the
database to end each database session. However, if you forget, Java's garbage collector will
close the connection when it cleans up stale objects. Relying on the garbage collection,
especially in database programming, is a very poor programming practice. You should make a
habit of always closing the connection with the close() method associated with connection
object.

To ensure that a connection is closed, you could provide a 'finally' block in your code.
A finally block always executes, regardless of an exception occurs or not. To close the above
opened connection, you should call close() method as follows

conectionObject.close()

Once a connection is obtained we can interact with the database. The JDBC Statement,
CallableStatement, and PreparedStatement interfaces define the methods and properties that
enable you to send SQL or PL/SQL commands and receive data from your database. They also
define methods that help bridge data type differences between Java and SQL data types used in a
database.

Interfaces Recommended Use


Statement Use statement for general-purpose access to your database. Useful
when you are using static SQL statements at runtime. The Statement
interface cannot accept parameters.
PreparedStatement Use when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
CallableStatement Use when you want to access database stored procedures. The
CallableStatement interface can also accept runtime input parameters.

The Statement Object:


Creating Statement Object: Before you can use a Statement object to execute a SQL
statement, you need to create one using the Connection object's createStatement( ) method, as
in the following example:
Statement stmt = null;
try {
stmt = conn.createStatement( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}

Once you've created a Statement object, you can then use it to execute a SQL statement with
one of its three execute methods.

1 boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can
be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements
or when you need to use truly dynamic SQL.

2 int executeUpdate(String SQL) : Returns the numbers of rows affected by the execution
of the SQL statement. Use this method to execute SQL statements for which you expect
to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE
statement.

3 ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use this method


when you expect to get a result set, as you would with a SELECT statement.

Closing Statement Object: Just as you close a Connection object to save database resources,
for the same reason you should also close the Statement object. A simple call to the close()
method will do the job. If you close the Connection object first it will close the Statement
object as well. However, you should always explicitly close the Statement object to ensure
proper cleanup.

Statement stmt = null;


try {
stmt = con.createStatement( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
stmt.close();
}

The PreparedStatement Object:


The PreparedStatement interface extends the Statement interface which gives you added
functionality with a couple of advantages over a generic Statement object.
This statement gives you the flexibility of supplying arguments dynamically.
Creating PreparedStatement Object:
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally { . . .}

All parameters in JDBC are represented by the ? symbol, which is known as the parameter
marker. You must supply values for every parameter before executing the SQL statement.

The setXXX() methods bind values to the parameters, where XXX represents the Java data
type of the value you wish to bind to the input parameter. If you forget to supply the values,
you will receive a SQLException.

Each parameter marker is referred to by its ordinal position. The first marker represents
position 1, the next position 2, and so forth. This method differs from that of Java array
indices, which start at 0.

All of the Statement object's methods for interacting with the database (a) execute(), (b)
executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object.
However, the methods are modified to use SQL statements that can take input the parameters.

Closing PreparedStatement Object: Just as you close a Statement object, for the same
reason you should also close the PreparedStatement object. A simple call to the close()
method will do the job. If you close the Connection object first it will close the
PreparedStatement object as well. However, you should always explicitly close the
PreparedStatement object to ensure proper cleanup.

PreparedStatement pstmt = null;


try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
. . .}
catch (SQLException e) { . . .}
finally { pstmt.close();
}

The Callable Statement Object:

Just as a Connection object creates the Statement and PreparedStatement objects, it also creates
the CallableStatement object which would be used to execute a call to a database stored
procedure. Using CallableStatement objects is much like using PreparedStatement objects. You
must bind values to all parameters before executing the statement, or you will receive an
SQLException. Just as you close other Statement object, for the same reason you should also
close the CallableStatement object. A simple call to the close() method will do the job. If you
close the Connection object first it will close the CallableStatement object as well. However, you
should always explicitly close the CallableStatement object to ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall(SQL);
. . .}
catch (SQLException e) { . . .}
finally {
cstmt.close();
}

The ResultSet Object:


A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is
positioned before the first row. The next method moves the cursor to the next row, and because it
returns false when there are no more rows in the ResultSet object, it can be used in a while loop
to iterate through the result set.
A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you
can iterate through it only once and only from the first row to the last row. It is possible to
produce ResultSet objects that are scrollable and/or updatable.
The ResultSet interface provides getter methods (getBoolean, getLong, and so on) for retrieving
column values from the current row. Values can be retrieved using either the index number of the
column or the name of the column. In general, using the column index will be more efficient.
Columns are numbered from 1. For maximum portability, result set columns within each row
should be read in left-to-right order, and each column should be read only once.
Types of ResultSet:

Type Description

ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result


set.

ResultSet.TYPE_SCROLL_INSENSITIV The cursor can scroll forward and backward, and


E the result set is not sensitive to changes made by
others to the database that occur after the result
set was created.

ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward, and


the result set is sensitive to changes made by
others to the database that occur after the result
set was created.

Difference between Scrollable ResultSet and Non-Scrollable ResultSet

Non-Scrollable ResultSet Scrollable ResultSet


Cursor can move both forward and
Cursor move only in forward direction
backward direction
Slow performance, If we want to move nth record then Fast performance, directly move on any
we need to n+1 iteration record.
Non-Scrollable ResultSet cursor can not move Scrollable ResultSet cursor can move
randomly randomly

The possible ResultSet Concurrency are given below. If you do not specify any Concurrency
type, you will automatically get one that is CONCUR_READ_ONLY.

Concurrency Description

ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the default

ResultSet.CONCUR_UPDATABLE Creates an updateable result set.

Methods of Scrollable ResultSet:


afterLast Used to move the cursor after last row.

BeforeFirst: Used to move the cursor before first row.

previous: Used to move the cursor backward.

first: Used to move the cursor first at row.

last: Used to move the cursor at last row.

1.6 Executing SQL commands

To execute a query, call an execute method from Statement such as the following:
execute: Returns true if the first object that the query returns is a ResultSet object. Use this
method if the query could return one or more ResultSet objects. Retrieve theResultSet objects
returned from the query by repeatedly calling Statement.getResultSet.
executeQuery: Returns one ResultSet object.
executeUpdate: Returns an integer representing the number of rows affected by the SQL
statement. Use this method if you are using INSERT, DELETE, or UPDATE SQL statements.

Example:

ResultSet rs = stmt.executeQuery(Select * from Employee);

**********************End of Chapter*******************************

Assignment 1: JDBC
1 Write down the steps involved in creating a JDBC application.
2 Explain JDBC architecture with suitable diagram.
3 Explain the types of drivers used in JDBC.
4 Explain the types of statements used in JDBC in detail.

Vous aimerez peut-être aussi