Introduction to Programming
with
Java
1
Chapter 3
Database Programming
2
JDBC Introduction
Java Data Base Connectivity(JDBC) is a set of Java APIs used for
executing SQL statements.
JDBC is much similar to Microsoft’s Open Database Connectivity(ODBC)
interface to SQL (Structure Query Language).
JDBC API is a set of interfaces and classes to be used for communicating
with a database. These interfaces and classes are found in the java.sql
package.
JDBC allows developers to write client/server properties in Java.
JDBC is an interface that stands between the specific database and the Java
applications, applets and Servlets.
Why JDBC is advantageous with Java? The reason behind that is programs
developed with the java programming language and JDBC are platform
independent.
3
Role of JDBC
Establishes connection with the database.
Sends SQL statements.
Process the results
Close the connection.
4
JDBC Characteristics
It is call-level SQL interface for Java.
It does not restrict the type of queries of passed to an underlying
DBMS driver.
JDBC mechanisms are simple to understand and use.
It provides Java Interface that stays consistent with the rest of the
Java system.
5
The Design of the JDBC
At the initial, when the Sun team wants to built the database
they extends the standard Java Library to deal with the SQL
access to database. Because of this it is impossible task it didn’t
take them very long to realize.
Afterwards with the help of networking protocols Sun works on
the pure java API for the SQL access.
Then much of time later the API for the database access
become the JDBC API, and the rules for writing drivers were
encapsulated in the JDBC driver API.
6
The Design of the JDBC
Simple Design
JDBC consists of two layers: the top layer is the JDBC API and the bottom layer is
the JDBC driver API
Java Application
JDBC Driver Manager
JDBC/ODBC Vender supplied
Bridge JDBC driver
ODBC
driver
Data Base
Server
Data Base
Server
7
The Design of the JDBC
Simple Design
The top layered API communicates with the JDBC manager
driver API sending it the various SQL statements.
Afterwards the manager communicates with the various third
party drivers that actually connect to the database and return the
information from the query or perform the action specified by
the query.
The Driver Manager also helps to select the most appropriate
driver from the previously loaded drivers when a new open
database is connected.
8
The Design of the JDBC
Two – tier and Three – tier Models
Two – tier Model
Java applications/applets interact directly with the database.
This model is referred to as client/server model where user is the client and the machine
that has the database is called the server.
First the is the JDBC API layer and second is the various third party drivers.
Java Application
Client Machine (GUI)
JDBC
DBMS proprietary protocol
DBMS Database Server
9
The Design of the JDBC
Two – tier and Three – tier Models
Three – tier Model
A middle tier is introduced in this model.
Uses of the middle tier:
It collects the SQL statement from the client and hands it over to the database.
Receives results from the database to the client.
Controls accessing and updating of data.
This three tier architecture introduces the Java API calls the middleware layer that in turn
accesses the data. Java Applet or Client Machine (GUI)
HTML browser
HTTP, RMI or COBRA calls Remote Method Invocation
Application
Server(Java)
Server machine (Business Logic)
JDBC
DBMS proprietary protocol
DBMS Database Server eg. SQL Server
Oracle
10
The Design of the JDBC
Two – tier and Three – tier Models
Three – tier Model
11
JDBC Drivers
The JDBC driver translates standard JDBC calls into a network
or database protocol or into a database library API call that
facilitates communication with the database.
This translation layer provides JDBC application with database
independence. If the back-end database changes, only the JDBC
driver need to be replaced with few code modifications
required.
12
Type 1: JDBC ODBC Bridge Driver
PREPARED BY ALLAUDIN “HEMAT” 13
Type 1: JDBC ODBC Bridge Driver
Type 1 drivers act as a “bridge” between JDBC and another database
connectivity mechanism such as ODBC.
Sun provided a JDBC-ODBC Bridge driver:
sun.jdbc.odbc.JdbcOdbcDriver.
In this driver the java statements are converted to jdbc statement.
JDBC statements call the ODBC by using the JDBC-ODBC Bridge. And
finally the query is executed by the database.
This bridge is helpful for testing but it cannot recommend for the
production used.
Type 1 only runs on platforms where ODBC is available.
This driver is native code and not Java i.e it is written in C or C++
language not in Java
14
Type 2: Native-API Driver
15
Type 2: Native-API Driver
Type 2 driver converts JDBC API calls to the native C or C++
API calls.
This driver converts the JDBC calls into a database specific call
for databases such as SQL, ORACLE etc.
This driver communicates directly with the database server. It
require some native code to connect to the database.
Type 2 drivers are usually faster than type 1 drivers.
16
Type 3: Network Protocol Driver
17
Type 3: Network Protocol Driver Or All-Java
Driver
Type 3 drivers are pure Java drivers that use a proprietary
network protocol to communicate with JDBC middleware on
the server.
The middleware then translates the network protocol to
database-specific function call.
Type 3 drivers can be deployed over the Internet without client
installation. Java----> JDBC statements-----> SQL statements
----->databases.
18
Type 4: Database Protocol Driver
19
Type 4: Database Protocol Driver
The JDBC type 4 driver, also known as the Direct to
Database Pure Java Driver, is a database driver
implementation that converts JDBC calls directly into a vendor-
specific database protocol.
Written completely in Java, type 4 drivers are thus platform
independent.
They install inside the Java Virtual Machine of the client.
20
JDBC API
Interfaces in java.sql package
Interfaces Methods
Array getArray(), getBaseType, getResultSet
Blob getBinaryStream, getBytes, length, position
CallableStatement registerOutParameter, wasNull
getAsciiStream, getCharacterStrea, getSubString,
Clob
length, position
commit, createStatement, isClosed, isReadOnly,
Connection
rollback
DatabaseMetadata getColumns, getConnection,
absolute, afterLast, beforeFirst, close, next, previous,
ResultSet
deleteRow, insertRow
cancel, close, executeUpdate, getConnection,
Statement
getMaxRows
PREPARED BY ALLAUDIN “HEMAT” 21
JDBC API
Classes in java.sql package
Classes Methods
Date getHours, getMinutes, setTime, toString, valueOf
DriverManager getConnection, println, registerDriver, getDriver
Time getDate, getYear, getMonth, setTime, setYear
PREPARED BY ALLAUDIN “HEMAT” 22
Essential JDBC progam
Steps for using JDBC to access Database
1) Import the java.sql package
import java.sql.*;
2) Load a JDBC driver
All drivers are required to register themselves at load time.
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e)
{
System.out.println("Unable to load the driver...");
}
PREPARED BY ALLAUDIN “HEMAT” 23
Essential JDBC progam
Steps for using JDBC to access Database
3) Connect to the database
The JDBC DriverManager Class defines objects which can connect
java applications to a JDBC driver, which is backbone of JDBC
architecture.
getConnection() method used to establish connection.
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/db_hms","root","");
4) Create a statement
To execute SQL statements, we need to initiate a statement object
form our connection object by using createstatement() method.
con.createstatement();
PREPARED BY ALLAUDIN “HEMAT” 24
Essential JDBC progam
Steps for using JDBC to access Database
There are 3 types of statement
1) Statement: Simple SQL queries without parameters.
2) Prepared Statement: Executed precompiled SQL queries with or
without parameters. PrepareStatement objects are precompile SQL
statement.
3) Callable Statement: Execute a call to a database stored procedure.
CallableStatement objects are SQL stored procedure call statements
5) Execute the statement
stmt.exeuteUpdate(String str);
To exeute query executeQuery() methods comes in picture. The
executeQuery() method takes SQL query as a parameter and returns
the result of the query as the ResultSet Object.
25
Essential JDBC progam
Steps for using JDBC to access Database
Result rs1=stmt.executeQuery("Select id, name,salary from teacher
where department="Computer" ");
6) Retrieve the result
while(rs1.next())
{
int x=rs1.getInt(1);
String s=rs1.getString("b");
}
The above is just an example where rs1 is a ResutlSet object. The results
of the SQL statements are stored in a ResultSet object. To retrieve the
data from this object, we use the getXXX methods. To move to the next
row, we make use of rs1.next() method.
26
Essential JDBC progam
Steps for using JDBC to access Database
7) Close the statement and the connection:
stmt.close();
con.close();
con.commit();
PREPARED BY ALLAUDIN “HEMAT” 27
Essential JDBC progam
Steps for using JDBC to access Database
Write JDBC program to accept employee information from
database and update first tuple and display after updating.
Write JDBC program that insert the following details to a teacher
table having the following structure.
teacher_name, department, salary
28