You are on page 1of 18

APC Ray Polytechnic

188, Raja Subodh Chandra Mallick Rd, Jadavpur,


Kolkata - 700032
Department of Computer Science & Technology
3rd year – 5th semester
e-Contents : Java Programming
Unit 7 : Database Connectivity: JDBC

Developed By:
Prosenjit Roy
Lecturer In Computer Science & Technology
APC Ray Polytechnic
188, Raja Subodh Chandra Mallick Rd, Jadavpur,
Kolkata - 700032
Java Programming : Unit 7

Contents

Subunit

7.1 Java Database Client/Server


7.1.1 Java as Database Front-End
7.1.2 Database client/server methodology
7.1.3 Database client/server Architecture
7.1.3.1 Two-Tier Database Design
7.1.3.2 Three-Tier Database Design

7.2 The JDBC API


7.2.1 The API Components
7.2.2 JDBC Drivers
7.2.2.1 JDBC-ODBC Bridge
7.2.2.2 Current JDBC Drivers

7.2.3 A JDBC Database Example


7.2.4 Limitations Using JDBC
7.2.5 Security Considerations

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 2
Java Programming : Unit 7

Database Connectivity: JDBC


JDBC: A Brief Introduction:
What is JDBC?
JDBC API is a Java Application Programme Interface that can access any kind of tabular data, especially
data stored in a Relational Database. JDBC works with Java on a variety of platforms, such as Windows,
Mac OS, and the various versions of UNIX.
JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent
connectivity between the Java programming language and a wide range of databases.
The JDBC library includes methods for each of the tasks mentioned below that are commonly associated
with database usage:
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Sending SQL or MySQL queries to the database.
 Viewing & Modifying the resulting records.

Applications of JDBC:
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable
access to an underlying database. It is the duty of each JDBC driver to implement these interfaces
according to the DBMS it will be catering.
Java can be used to write different types of executables, such as −
 Java Applications
 Java Applets
 Java Servlets
 Java Server Pages (JSPs)
 Enterprise Java Beans (EJBs).
All of these different executables are able to use the JDBC API to access a certain database through a
suitable JDBC driver catering the specific DBMS managing the database.
Some database vendors already have JDBC drivers (e.g. Oracle). For those databases that do not have a
JDBC driver, you need to install the database's ODBC driver and the JDBC to ODBC Bridge supplied
by JavaSoft. The JDBC to ODBC Bridge has the advantage of letting the Java application programmer
have access to almost any database since the ODBC drivers are readily available for most databases. It
has the disadvantage of requiring yet another layer between the database and the JDBC, although in most
cases the performance is acceptable.
Sun’s Java-based JDBC provides the same capabilities as its elder counterpart viz. Microsoft’s C-based
ODBC, allowing Java programs to access diverse databases with database-independent code.

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 3
Java Programming : Unit 7

Fig: JDBC to Database communication path

7.1 Java Database Client/Server:


7.1.1 Java as Database Front-End:
Java offers several benefits to the developer creating a front-end application for a database server. Java is
‘Write Once Run Everywhere’ language. This means that Java programs may be deployed without
recompilation on any computer architecture and operating system that possesses a Java Virtual
Machine.

Yet, in spite of having such alluring potential, when Sun Microsystems originally released JDK 1.0 in
early 1995, Java was hugely handicapped by the fact that it had no integrated support for accessing
databases, and hence was not able to become an industrial-strength programming language.

JavaSoft saw the prospect of chaos in the marketplace and responded with the first release of the Java
Database Connectivity (JDBC) specification in May, 1996. The JDBC specification, guided by Rick
Cattell and Graham Hamilton at JavaSoft, has structural and conceptual similarities with Microsoft's C-
based Open Database Connectivity driver, which Microsoft introduced in the 1980s to bring some
conformity to client access to databases.

But in those early days, there were very few JDBC drivers from any database vendor, as would be
expected with any new technology — but the ODBC ecosystem, itself then at only v 2.0, was going
strong.

Sun recognized that Java wouldn’t have as much uptake without a functional data access solution — so
they came up with a prompt solution in the form of the JDBC-ODBC Bridge driver viz.

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 4
Java Programming : Unit 7

sun.jdbc.odbc.JdbcOdbcDriver to allow JDBC clients to connect to the database via a suitable ODBC
driver that were readily available in abundance.

As Java has gained favour as the language of choice for Internet and intranet applications, the number of
choices for JDBC drivers has grown. DBMS manufacturers and third-party vendors are increasingly
encouraged to build JDBC drivers that conformed to Sun’s specifications. Those firms that build JDBC
drivers for their product can tap into the growing Java applications market.

This is how Java has evolved to become a much-coveted top-notch front-end in the database-market.

Architecture of the JDBC framework:


Right at the top of this architecture operates the Java applications that try to access the database with
various queries scripted in Structured Query Language (SQL) which was the first commercial query
language introduced for the Relational model of database developed by E. F. Codd at the IBM San Jose
Research Lab in the 1970s. Today almost all RDBMSs (Oracle, MySQL, Sybase, MS Access etc.)
use SQL as the standard database query language.
The JDBC API acts as the programming interface for the Java applications to SQL statements.
The JDBC API communicates with yet another intermediate API viz. the JDBC Driver Manager API,
forwarding it various SQL statements supplied by the Java applications. The driver manager
communicates with the various third party drivers (provided by database vendors like Oracle) that
actually connect to the database and return the result of the query.
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 block diagram depicts the architectonic relation prevailing among the various entities of the
JDBC framework:

Fig: Architecture of JDBC Framework

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 5
Java Programming : Unit 7

7.1.2 Database Client/Server methodology:


The Client/Server Model:
Generally speaking, Client-Server model is a distributed application structure that partitions workloads
between the providers of a service, called servers, and service requesters, called clients. Often clients and
servers communicate over a computer network on separate hardware, though both client and server may
reside in the same system. A server host runs one or more application programmes called the server
programmes, which share the server’s resources with clients. A client host, on the other hand, does not
share any of its resources, but it requests resources from a server through application programmes called
the client programmes that run on it. Clients, therefore, depending on their need, initiate finite
communication sessions with servers, which await incoming requests infinitely.

In a more technical sense, it is the server programme and the client programme themselves (in the
running state) that are meant by the terms server and client respectively - not the hardware devices on
which they run.

The Database Client and the Database Server:


In the database client/server architecture, the database application and the database are separated into two
distinct parts: a front-end or client end, and a back-end or server end respectively. The client sends
requests in the language SQL. The server responds with data and status messages. Clients and servers
generally reside on separate hardware belonging to different computer networks connected via Internet,
though both client and server may reside in the same system, in which case they communicate using
socket file.

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 6
Java Programming : Unit 7

Database servers are actually the database management system (DBMS) software (like, e.g., Oracle,
MySQL, Db2 etc.) that interact with the data source i.e. the database. Database clients, on the other hand,
are application programmes written in Java, PHP etc., which generate SQL statements, and send them to
the server.
The pattern for interaction is as follows:
 The Client issues forth a database query in the form of an SQL statement.
 The Server returns a status code, and maybe some data.
Suppose you want your Java programme to load some data to a MySQL database.

Your programme sends an SQL statement that includes the INSERT statement with the data values to be
inserted.
The DBMS executes the SQL statement, and returns a status code, like ―OK.‖

7.1.3 Database Client/Server Architecture:


Database client/server architecture depends upon how clients i.e. the database applications are connected
to the server i.e. the DBMS to get their requests served. From this perspective, database client-server
architecture is of two types:
 Two-tier architecture
 Three-tier architecture

7.1.3.1 Two-tier Database Design:


The first generation of client-server architectures is called two-tiered. It contains two active components:
the client, which requests data, and the server, which delivers data. Here the application’s processing is
split into two distinct parts and done separately on the client and the server. The client looks after the
processing of the user interface presentations, whereas the server performs the processing of the database
queries and updates. For example, thousands of airline ticket reservation applications can connect to a
central DBMS to request, insert, or modify data. While the clients process the graphics and data entry
validation, the DBMS does all the data processing. Figure below illustrates the Two-tier architecture:

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 7
Java Programming : Unit 7

7.1.3.2 Three-tier Database Design:


To avoid embedding the application’s logic at both the server side and the client side, a third software tier
may be inserted. The Three-tier architecture is split into 3 separate logical layers, namely, the User-
Interface layer (Presentation Tier), the Application layer (Business Tier) and the Database layer (Data
Tier). The Client system manages the User-Interface layer where the processing of the user interface
presentations is done; the Application server takes care of the Application layer, which sits in the middle
and where most of the business logic is frozen, and the Server system supervises Database layer, where
the processing of the database queries and updates takes place. In this architecture, when the business
activity or business rules change, only the middleware must be modified. Almost all the modern-day
database application systems use the Three-tier architecture. Our popular online railway ticket booking
system fondly known to us as ―irctc‖, is a very good example that uses this type of architecture. Figure
below illustrates the Three-tier architecture.

7.2 The JDBC API:


JDBC API was released as part of Java Development Kit (JDK) 1.1 on February 19, 1997 by the then
Sun Microsystems, Inc (which is now acquired by the Oracle Corporation). Since then it has been part
of the Java Standard Edition (Java SE).
The JDBC API, which now comes as JDBC 4.3 (the latest stable release till date), is contained in two
packages namely java.sql and javax.sql. The java.sql package contains core Java objects of JDBC API.
There are two distinct layers within the JDBC API: the Application layer, which database-application
developers use, and the Driver layer which the drivers’ vendors implement.

7.2.1 The JDBC API Components:


Among the components of the JDBC API, there are four main interfaces that every driver layer must
implement and one class that bridges the Application layer and the Driver layer. The class just referred is
DriverManager, and the four interfaces are Driver, Connection, Statement and ResultSet. The Driver
interface implementation is where the connection to the database is made. The SQLException class is
another class that will be of our interest.
Following is the brief overview of these interfaces and classes:

 DriverManager: This class manages a list of registered JDBC drivers as well as matches
connection requests from the java application with the proper JDBC driver using the
communication subprotocol supplied as a substring of the database URL that is passed as an

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 8
Java Programming : Unit 7

argument of one of its getConnection() method. The first driver that recognizes a certain
subprotocol under JDBC will be used to establish a database connection.
 Driver: This interface handles the communications with the database server. One will interact
directly with Driver objects very rarely. Instead, you use DriverManager objects, which are able
to manage objects of Driver. This will abstract the details associated with the working with
Driver objects.
 Connection: An object of Connection interface represents the connection session between
Java application and database. All that happens within the context of a connection – e.g. the
creation of SQL statements, the submission of them to the database, the returning of the results
by the database - take place through the connection object. By using the
createStatement()method of this interface one can obtain a Statement object that can then
be used to execute SQL statements. It also provides many methods for transaction management
like commit(), rollback() etc., and of course the close() method to terminate the
connection.
 Statement: The objects created from this interface are used to submit the database query to the
database through its executeQuery(String s)/executeUpdate(String s)
method that contains the SQL statement as its argument. Some of its derived interfaces accept
parameters or execute stored procedures. This interface has the following two useful sub-
interfaces:
 PreparedStatement: It is used to execute parameterized query. An SQL statement is
precompiled and stored in a PreparedStatement object using the
prepareStatement(String s) method of the Connection interface. This object
can then be used to efficiently execute this statement multiple times using first its
setXXX() methods, and then its executeQuery(void)/executeUpdate(void)
method.
 CallableStatement: This sub-interface of PreparedStatement is used to execute an
SQL stored procedure which is a parameterized block of code and is identified by a unique
name. A stored procedure can be created by the following SQL command:
CREATE PROCEDURE <sp_name>(<parameter_list>)
IS
BEGIN
//statements;
END;
A stored procedure can be executed by the SQL command as follows:
EXECUTE <sp_name>(<parameter_list>);
An SQL statement containing the stored procedure call is first stored in a CallableStatement
object using the prepareCall(String s) method of the Connection interface. This
object can then be used efficiently to execute this statement with the assistance of its
setXXX(), getXXX()and executeQuery(void)/executeUpdate(void)
methods.
 ResultSet: The objects of this interface hold tabular data retrieved from a database after you
execute an SQL query using Statement objects. It contains many getXXX() methods to extract
specific data from the table returned by the database. It contains a method called next()that

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 9
Java Programming : Unit 7

allows the Java application to move down the rows of the table that it holds, starting from the top
row.
 SQLException: This class handles any errors that occur in a database application.

Time

Fig: Hierarchy of the JDBC API components as per the sequence of their usage

7.2.2 JDBC Drivers:

What is a JDBC Driver?

JDBC drivers are basically client-side adapters (i.e. a piece of software), installed on the client machine,
not on the server, that convert requests from Java programs to a protocol that the DBMS it is catering
can understand.
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with their respective
database servers.
JDBC drivers enable Java Applcations to connect to the database, to interact with it by sending SQL
statements and then to retrieve the result returned by the database.
The Java.sql package that ships with JDK, contains various classes and interfaces with their general
behaviours outlined, and their actual implementaions are done in third-party drivers.

JDBC Driver Types:

Sun has defined four categories of JDBC drivers. The categories delineate the differences in architecture
for the drivers. One difference between architectures lies in whether a given driver is implemented in

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 10
Java Programming : Unit 7

native code or in Java code. Another difference lies in how the driver makes the actual connection to the
database.

The four driver types are as follows:

Type-1: JDBC-ODBC Bridge Driver:


As the name suggests, the JDBC-ODBC bridge driver makes use of ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
Type-1 driver is also called Universal driver because it can be used to connect to any database as long as
it provides an ODBC driver. This driver is implemented using native code.
Pros:
 Any database that provides an ODBC driver can be accessed
Cons:
 Features are limited and restricted to what ODBC driver is capable of
 Platform dependent as it uses ODBC which in turn uses native O/S libraries
 ODBC driver must be installed on client machine
 No support available from JDK 8 (1.8)
 Limited portability as ODBC driver may not be available for all platforms
 Data transferred through this driver is not so secured
Example: JDBC-ODBC Bridge driver of Sun (now Oracle).

Fig. Type-1 Driver

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 11
Java Programming : Unit 7

Type-2: Native API Driver:


The Native API driver uses existing client -side libraries of the database. This driver converts JDBC
method calls into native calls of the database API.
Pros:
 Faster than JDBC-ODBC bridge as there is no conversion like ODBC involved
 Data transfer is much more secure as compared to Type-1 driver
Cons:
 Vendor client side libraries needs to be installed on client machine
 Not written in Java, hence is platform dependent (i.e. not portable)
 Fully database dependent
 Not all database vendors provide client side libraries
Example: Oracle Call Interface (OCI) driver of Oracle.

Fig. Type-2 Driver

Type-3: Network Protocol driver:


The Network Protocol driver makes use of a middleware between the Java application and the database.
The middleware is an application server that converts JDBC calls directly or indirectly into the vendor-
specific database calls.
Pros:
 No need to install any vendor client side libraries on client machine
 Not vendor-specific. The same client-side driver may provide access to multiple databases
depending on the number of databases the middleware has been configured to support
 Purely written in Java, hence supports platform portability

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 12
Java Programming : Unit 7

 Middleware application server can provide additional supports like caching, load balancing,
logging, auditing etc.
 The middleware provides additional advantages of security
Cons:
 Maintenance of the middleware incurs additional costing
 May add extra latency as it goes through middleware server

Example: DataDirect SequeLink JDBC driver

Fig. Type-3 Driver

Type 4: Database (Native) Protocol Driver/Thin Driver:


The Database (Native) Protocol driver is also called Pure Java Driver. It converts JDBC calls directly
into vendor-specific database protocol. It does not require any native database library on the client
machine; that is why it is also known as Thin Driver. This is the highest performance driver available
for the database and is usually provided by the vendor itself.
Pros:
 No client-side or server-side installation is required
 Written completely in Java, hence platform independent
 Provides better performance than Type 1 and 2 drivers as no protocol specific conversion is
required
 Better than Type 3 drivers as it doesn’t need additional middleware application servers

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 13
Java Programming : Unit 7

 Connects directly to database drivers without going through any other layer
Cons:
 Database dependent
Example: MySQL's Connector/J driver

Fig. Type-4 Driver

Which Driver to choose?


 If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver is
Type-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 for your
database.
 The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.

7.2.2.1 The JDBC-ODBC Bridge:


When Sun Microsystems originally released JDK 1.0 in early 1996, Java had no data accessing feature.
At that time Microsoft’s C-based ODBC was the king in the database market. Sun responded to the call
of the hour and came up with JDK 1.1 that included the first release of JDBC i.e. JDBC 1.0 and the
original Type-1 JDBC-to-ODBC bridge driver viz. the ‘JDBC-to-ODBC Bridge’ defined in the
class sun.jdbc.odbc.JdbcOdbcDriver. It was a prompt, sensible and easy solution on Java’s part
to allow access to databases by using, as an intermediary, the ODBC drivers which were readily
available for most of the database vendors.

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 14
Java Programming : Unit 7

It was, in fact, the first strategic step to beckon the database application developers to migrate
from the old platform-dependent C/C++ world to the new much-alluring platform-independent
world of Java.

The JDBC-to-ODBC Bridge driver has always been a narrow-gauge driver, as it was conceived as a
transitional solution, and from the very beginning Sun warned that users should use this driver only for
experimental prototyping, or when they have no other pure JDBC driver available. With so many pure
JDBC drivers having already made it to the market, that is a decent justification of why Sun, to be exact
Oracle, removed it in Java 8.

Though, we must not forget that in those formative days in the mid ′90s of the last century, when the
JDBC drivers were at a premium, the Bridge was quite helpful as it provided the JAVA DB application
developers with an easy, almost panacea-like option. So, for one last time, here is to the Bridge!

The database URL format for the JDBC-to-ODBC Bridge:


jdbc:odbc:<DSN_name> // ‘jdbc’ ->Protocol, ‘odbc’ -> subprotocol

7.2.2.2 Current JDBC Drivers:


Following table lists down the popular JDBC drivers along with their database URL format:

RDBMS JDBC driver name URL format

MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName

ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port


Number:databaseName

DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port


Number/databaseName

Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port


Number/databaseName

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 15
Java Programming : Unit 7

7.2.3 A JDBC Database Example:

A Sample JDBC Code:


//STEP 1: Import required packages
import java.sql.*;

public class StudentData {

public static void main(String[] args) {

try
{
//STEP 2: Register JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

//STEP 3: Establisg a connection


System.out.println("Connecting to database...");
Connection con =
DriverManager.getConnection(“jdbc:odbc:student”,“cst”,“java”);

//STEP 4: Create a Statement Object


System.out.println("Creating statement...");
Statement st = con.createStatement();

//STEP 5: Execute a query


ResultSet rs = st.executeQuery("select * from Student where
Marks > 70");

//STEP 5: Extract data from result set


System.out.println("Students having marks > 70 are:");
while(rs.next()){

System.out.println(rs.getString(“Name”));

}
//STEP 7: Terminate the connection
con.close();
}
catch(Exception e)
{}
} // End of main()
} // End of class

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 16
Java Programming : Unit 7

Table Name: Student

Roll Name Marks


1 Amit 54
2 Sonali 78
3 Rahul 69
4 Priya 81
5 Tapan 73
6 Aditi 49

Output:
Students having marks > 70 are:
Sonali
Priya
Tapan

—The End of Unit 7—

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 17
Java Programming : Unit 7

References:

Books:
1. J2EE the Complete Reference by Jim Keogh

2. Java Programming: A Practical Approach by C. Xavier

3. Web Design Technology by D. P. Nagpal

Websites:
1. https://docs.oracle.com

2. https://www.javatpoint.com

3. https://www.geeksforgeeks.org

©Prosenjit Roy (Lecturer in Computer Sc. & Technology, APC Ray Polytechnic) Page 18

You might also like