You are on page 1of 30

JDBC

CHAPTER 1
JDBC
1.1. Basic JDBC Program Concepts
1.2. Design of JDBC
1.3. JDBC Driver
1.4. JDBC Architecture
1.5. Making the Connection in JDBC
1.6. Statement Objects
1.7. ResultSet
1.8. Executing SQL Commands
1.9. Executing Queries
Introduction

 JDBC stands for Java Database Connectivity. It is set of Java API’s (application programming
interface) used for executing SQL statements. This API consists of a set of classes and interfaces
to enable programmers to write pure Java Database applications.

 JDBC is a software layer that allows developers to write real client –server projects in Java. JDBC
does not concern itself with specific DBMS functions. JDBC API defines how an application
opens a connection, communicates with a database, executes SQL statements, and retrieves
query result.

 JDBC was designed to be very compact, simple interface focusing on the execution of raw SQL
statements and retrieving the results. The goal of creating JDBC is to create an interface that
keeps simple tasks, while ensuring the more difficult and uncommon tasks are at least made
possible.
Advantages of using Java with JDBC:
Some of the advantages of using Java with JDBC are as follows:
 Easy and economical.
 Continued usage of already installed databases.
 Development time is short.
 Installation and version control simplified.
Design of JDBC
The JDBC consists of two layers. The top layer is the JDBC API. This API communicates with the JDBC
manager driver API, sending it the various SQL statements. The manager should (transparently to the
programmer) communicate 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 JDBC
specification will actually allow you to pass any string to the underlying driver. The driver can pass this
string to the database.
Java Application
JDBC API
JDBC Driver Manager
JDBC Driver API
Vendor
JDBC/ODBC
Supplied JDBC
Bridge
Driver
ODBC Driver
Database

Database
Common JDBC Components:
The JDBC API provides the following interfaces and classes:

DriverManag
er

SQLExceptio Driver
n

ResultSet Connection

Statement
Common JDBC Components:
1) DriverManager:
This class manages a list of database drivers. Matches connection requests from the java application
with the proper database driver using communication subprotocol.
2) Driver:
This interface handles the communications with the database server. You will interact directly with
Driver objects very rarely. Instead, one can use DriverManager objects, which manages objects of this
type. It also abstracts the details associated with working with Driver objects
3) Connection:
This interface with all methods for contacting a database. The connection object represents
communication context, i.e., all communication with database is through connection object only.
4) Statement:
One uses objects created from this interface to submit the SQL statements to the database. Some
derived interfaces accept parameters in addition to executing stored procedures.
5) ResultSet:
These objects hold data retrieved from a database after you execute an SQL query using Statement
objects. It acts as an iterator to allow you to move through its data.
6) SQLException:
This class handles any errors that occur in a database application.
Drivers
Why do we need a DB driver?
 We can’t directly talk to the Data base server.
 Driver converts JDBC calls to DB specific calls
 For every database, we need a driver
Types of JDBC Drivers
• Type-1: JDBC-ODBC Bridge Driver
• Type-2: Native API Driver
• Type-3: Network Protocol Driver
• Type-4: Thin Driver
Type-1: JDBC-ODBC Bridge Driver
• JDBC-ODBC converts JDBC calls to ODBC calls and give it
to ODBC Driver.
• ODBC Driver interconverts the calls to native calls of the
DB API.
• Then Native calls will be understood by Vendor DB
Library and then Vendor DB Library will interconvert
calls to Vendor specific DB protocol.
Advantages:
• Easy to use.
• Can be easily connected to any database.
Disadvantages:
• Performance degraded because JDBC method call is
converted into the ODBC function calls.
• The ODBC driver needs to be installed on the client
machine.
Type-2: Native API Driver
• Native API Driver converts JDBC calls to native calls of the DB API
Advantage:
• performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
• The Native driver needs to be installed on the each client machine.
• The Vendor client library needs to be installed on client machine.
Type-3: Network Protocol Driver
• This Driver does not directly converts JDBC call,it
uses a middleware between the calling program
and Database.
• Middleware converts JDBC calls to Vendor specific
DB Protocol
Advantage:
No client side library is required because of
application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
1.Network support is required on client machine.
2.Requires database-specific coding to be done in the
middle tier.
3.Maintenance of Network Protocol driver becomes
costly because it requires database-specific coding to
be done in the middle tier.
Type-4: Thin Driver
• It converts JDBC calls directly to vendor specific DB
protocol.
• It is fastest Driver because it has minimum layer of
communication.
Advantage:
Better performance than all other drivers.
No software is required at client side or server side.
Disadvantage:
Drivers depend on the Database.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in general JDBC
Architecture consists of two layers:
Java Application

JDBC API

JDBC Drivers Manager

JDBC Drivers JDBC Drivers JDBC Drivers

Oracle SQL Server ODBC Data Sources


1) JDBC API:
This provides the application-to-JDBC Manager connection.

2) 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. Diagram above is the architectural diagram, which shows the location of the driver
manager with respect to the JDBC drivers and the Java application.
Steps To Connect Database In Java
Steps to connect database in java using JDBC are given below:( import java.sql*;)
1.Load the JDBC driver.
2.Connection.
3.Statement.
4.Execute statement.
5.Close database connection.
1. Load the JDBC driver:
First step is to load or register the JDBC driver for the database. Class class provides forName() method to
dynamically load the driver class.
Syntax: Class.forName("driverClassName");
To load or register OracleDriver class:
Syntax:
Class.forName("oracle.jdbc.driver.OracleDriver");
To load or register MS-Access Driver class:
Syntax:
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver");
2. Create connection:
Second step is to open a database connection. DriverManager class provides the facility to create a connection
between a database and the appropriate driver. To open a database connection we can call getConnection() method
of DriverManager class.
Syntax:
Connection connection = DriverManager.getConnection(url, user, password)
To create a connection with Oracle database:
Syntax:
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","user","password");  
To load or register MS-Access Driver class:
Syntax:
Connection conn=DriverManager.getConnection(“jdbc:odbc:DBSourceName”);

3.Create statement:
The statement object is used to execute the query against the database. Connection interface acts as a factory
for statement object. A statement object can be any one of the Statement,
CallableStatement, and PreparedStatement types .To create a statement object we have to call createStatement()
method of Connection interface. Connection interface also provides the transaction management methods like
commit() and rollback() etc.
Syntax:
Statement stmt=conn.createStatement();
Methods of Statement Object:
Once user creates a Statement object, they can then use it to execute a SQL statement with one of its three
execute methods.

boolean int ResultSet


execute(St executeUpda executeQuer
ring SQL) te(String SQL) y(String SQL)

Methods of Statement Object:


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.
Types of Statement Objects:
Following are the types of statement objects:

The PreparedStatement Objects The CallableStatement Objects

1) The PreparedStatement Objects:


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.
2) The CallableStatement Objects:
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.
Creating PreparedStatement Object
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 an SQLException.
Each parameter marker is referred 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 starts 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 input the
parameters.
Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only uses the IN parameter.
The CallableStatement object can use all the three.
Here are the definitions of each −
Parameter Description
IN A parameter whose value is unknown when the SQL statement is created. You bind
values to IN parameters with the setXXX() methods.

OUT A parameter whose value is supplied by the SQL statement it returns. You retrieve
values from the OUT parameters with the getXXX() methods.

INOUT A parameter that provides both input and output values. You bind variables with
the setXXX() methods and retrieve values with the getXXX() methods.
4. Execute statement:
Statement interface provides the methods to execute a statement.
To execute a statement for select query use below:
Syntax:
ResultSet rs = stmt.executeQuery(selectQuery);  

Methods of ResultSet:
The methods of the ResultSet interface can be broken down into three categories

Navigational Methods Get Methods

1) Navigational Methods:
These are used to move the cursor around.
2) Get Methods: Update Methods
These are used to view the data in the columns of the current row being pointed to by the cursor.
3) Update Methods:
These are used to update the data in the columns of the current row. The updates can then be updated in the
underlying database as well.
Navigating a Result Set:
There are several methods in the ResultSet interface that involve moving the cursor, including:
S.N. Methods & Description
1 public void beforeFirst() throws SQLException 
Moves the cursor to just before the first row
2 public void afterLast() throws SQLException 
Moves the cursor to just after the last row
3 public boolean first() throws SQLException 
Moves the cursor to the first row
4 public void last() throws SQLException 
Moves the cursor to the last row.
5 public boolean absolute(int row) throws SQLException 
Moves the cursor to the specified row
Navigating a Result Set:

S.N. Methods & Description


6 public boolean relative(int row) throws SQLException 
Moves the cursor the given number of rows forward or backwards from where it currently
is pointing.
7 public boolean previous() throws SQLException 
Moves the cursor to the previous row. This method returns false if the previous row is off
the result set
8 public boolean next() throws SQLException 
Moves the cursor to the next row. This method returns false if there are no more rows in
the result set
9 public int getRow() throws SQLException 
Returns the row number that the cursor is pointing to.
10 public void moveToInsertRow() throws SQLException 
Moves the cursor to a special row in the result set that can be used to insert a new row
into the database. The current cursor location is remembered.
11 public void moveToCurrentRow() throws SQLException 
Moves the cursor back to the current row if the cursor is currently at the insert row;
otherwise, this method does nothing
Updating a Result Set:
The ResultSet interface contains a collection of update methods for updating the data of a result set.
As with the get methods, there are two update methods for each data type:
One that takes in a column name.
One that takes in a column index.
For example, to update a String column of the current row of a result set, you would use one of the following
updateString() methods:

S.N. Methods & Description


1 public void updateString(int columnIndex, String s) throws SQLException
Changes the String in the specified column to the value of s.
2 public void updateString(String columnName, String s) throws SQLException
Similar to the previous method, except that the column is specified by its name
instead of its index.
S.N. Methods & Description
1 public void updateRow()
Updates the current row by updating the corresponding row in the database.
2 public void deleteRow()
Deletes the current row from the database
3 public void refreshRow()
Refreshes the data in the result set to reflect any recent changes in the
database.
4 public void cancelRowUpdates()
Cancels any updates made on the current row.
5 public void insertRow()
Inserts a row into the database. This method can only be invoked when the
cursor is pointing to the insert row.
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to
before the first row.
Note:By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as
well as we can make this object as updatable by:
Syntax:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,  
                     ResultSet.CONCUR_UPDATABLE);  
5.Close database connection:
After done with the database connection we have to close it. Use close() method of Connection interface to
close database connection. The statement and ResultSet objects will be closed automatically when we close the
connection object.
Syntax:
conn.close();
 
Executing SQL Commands
Structured query language(SQL) is a standardized language that allows you to perform operations on a
database. Such as creating entries, reading content, updating content and deleting entries.
SQL is supported by almost any database you will likely use, and it allows you to write database code
independently of the underlying database.
Here I am giving an Overview of SQL, which is required to understand JDBC concepts. After going through
this ,you will be able to Create, Read,Update and Delete data from a database.
Create Database:
The create database statement is used for creating a new database.
Syntax:
create database database_nm;
e.g. Create database Cust;
Drop Database:
It is used for deleting an existing database.
Syntax:
drop database database_nm;
e.g. drop database Cust;
Create Table
It is used to create a new table
Syntax:
create table table_nm (column_nm column_data_type, column_nm column_data_type…….);
e.g. create table Student(sid int not null,name varchar(225),primary key(sid));
Drop table
used for deleting an existing table
Syntax:
drop table table_nm;
e.g. drop table Student;
Insert data
used for inserting data into created table
Syntax:
insert into Student values(1,’Ash’);
Select data
used to retrieve data from a database
e.g. Select sid,name from Student where sid=1;

The where clause can use the comparison operators such as =,!=,<,>,<= and >=, as well as the BETWEEN and LIKE
operators
e.g.
select sid, name from Student where name LIKE ‘%Ash%’;
This sql statement selects sid and name column from the student table, where name column contain Ash;
Update data
used to update data
Syntax:
update table_nm set colu_nm=value,colu_nm=value…… where conditions;
e.g.
update Student set name=‘Anu’ where sid=1;
Delete data
used to delete data from tables
Syntax:
delete from table_nm where condition;
e.g.
delete from Student where sid=1;

You might also like