You are on page 1of 38

Unit – I

Chapter - V
JDBC

Asst. Prof. Jyoti Samel KSD Model College


Where data store? Database

Java, C, c++, Python, HTTL, PHP ….. Software


Why we develop the s/w ? s/w are just mean to access the db

Facebook
Frontend
Facebook.com
Creating account by clicking Sing Up
1. Username ___________
2. Password _________
3. Submit
4. Facebook request to create a new account 🡪 registration details will
get it store within database.

Second time or further I am accessing facebook.com


Sing in
Username __________
Password ______________
🡪 It will validate the details
Asst. Prof. Jyoti Samel KSD
Model College
Java
Applications

Database
Java, servlet, HTTP
MySQL, Acccess,
form, JSP, etc….
JDBC fill the gap Oracle, hadoop,
Between the frontend Sqllite etc.
And the backend

frontend backen
d
CAR :
OLA Book :
BUS :
Train:
Hire Driver

JDBC – I am a medium of communication between s/w and database. But it


is upto u which driver u r going to hire?
This means JDBC gives me Driver types : there are 4 types of Drivers.

Asst. Prof. Jyoti Samel KSD


Model College
I want to ask AMAL
1. Call AMAL
2. New Mobile
3. Sim card , registration , it will be identified , recharge , charge the phone
battery
4. AMAL contact number : AMAL DIAL
5. My call will get connected with AMAL Phone 🡪 Ring
6. While RINGING 🡪 my brain is thinking or formatting a statement
7. AMAL Pick up the call 🡪 from this side I will start asking the question ,
giving instruction , I will pass the information .
8. END the call

9. I want to create a table


create table AMAL (flkdjflkjdfjdkfjdsfkd);
executeQuery();

Insert into AMAL values (1,1111);


executeUpdate();

Retrieve : AMAL send me the data


Select * from AMAL
ExecuteQuery() Asst. Prof. Jyoti Samel KSD
Model College
Microsoft's ODBC
Many database servers use vendor-specific protocols.
This means that a database client has to learn a new
language to talk to a different database server. However,
Microsoft established a common standard for
communicating with databases, called Open Database
Connectivity (ODBC). Until ODBC, most database
clients were server-specific. ODBC drivers abstract
away vendor-specific protocols, providing a common
application-programming interface to database clients.
By writing your database clients to the ODBC API, you
enable your programs to access more database servers.

Asst. Prof. Jyoti Samel KSD Model College 5


Microsoft's ODBC

Asst. Prof. Jyoti Samel KSD Model College 6


Comes JDBC ...
JDBC provides a common database-programming API for Java programs.
However, JDBC drivers do not directly communicate with as many databases using ODBC.
In fact, one of the first JDBC drivers was the JDBC-ODBC bridge driver developed by
JavaSoft and Intersolv.

Why did JavaSoft create JDBC?


What boil down to the simple fact that ODBC is a better solution for Java applications and
applets:

• ODBC is a C language API, not a Java (object-oriented and C is not) API. C uses
pointers and other "dangerous" programming constructs that Java does not support. A Java
version of ODBC would require a significant rewrite of the ODBC API.

• ODBC drivers must be installed on client machines. This means that applet access to
databases would be constrained by the requirement to download and install a JDBC driver.
A pure solution allows JDBC drivers to be automatically downloaded and installed along
with applet. This greatly simplifies database access for applet users.

Asst. Prof. Jyoti Samel KSD Model College 7


JDBC
Java Database Connectivity(JDBC) is an Application
Programming Interface(API) used to connect Java
application with Database.
JDBC is used to interact with various type of Database such as
Oracle, MS Access, My SQL and SQL Server.
JDBC can also be defined as the platform-independent
interface between a relational database and Java programming.
It allows java program to execute SQL statement and retrieve
result from database.
The JDBC API consists of classes and methods that are used to
perform various operations like:
�connect, read, write and store data in the database.

Asst. Prof. Jyoti Samel KSD Model College 8


JDBC

Asst. Prof. Jyoti Samel KSD Model College 9


How many drivers are there in JDBC?

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. There are 4 types of JDBC drivers:
Type-1 driver or JDBC-ODBC bridge driver
Type-2 driver or Native-API driver
Type-3 driver or Network Protocol driver
Type-4 driver or Thin driver

Asst. Prof. Jyoti Samel KSD Model College 10


Type-1 driver
Type-1 driver or JDBC-ODBC bridge driver uses 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 of the databases.
1. As a common driver is used in order to interact with different
databases, the data transferred through this driver is not so secured.
2. The ODBC bridge driver is needed to be installed in individual
client machines.
3. Type-1 driver isn’t written in java, that’s why it isn’t a portable
driver.
4. This driver software is built-in with JDK so no need to install
separately.
5. It is a database independent driver.

Asst. Prof. Jyoti Samel KSD Model College 11


Type-1 driver

Asst. Prof. Jyoti Samel KSD Model College 12


Type-1 driver
Advantage
The JDBC-ODBC Bridge allows access to almost any database,
since the database's ODBC drivers are already available.

Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers
are not portable.
2. A performance issue is seen as a JDBC call goes through the
bridge to the ODBC driver, then to the database, and this applies
even in the reverse process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the
driver.
4. Not good for the Web.

Asst. Prof. Jyoti Samel KSD Model College 13


Type-2 driver
The Native API driver uses the client -side libraries of the database.
This driver converts JDBC method calls into native calls of the
database API. In order to interact with different database, this driver
needs their local API, that’s why data transfer is much more secure
as compared to type-1 driver.
1) Driver needs to be installed separately in individual client
machines
2) The Vendor client library needs to be installed on client machine.
3) Type-2 driver isn’t written in java, that’s why it isn’t a portable
driver
4) It is a database dependent driver.
It is also not entirely written in java language. This causes the
portability issues and as this driver is database specific.

Asst. Prof. Jyoti Samel KSD Model College 1


Type-2 driver

Asst. Prof. Jyoti Samel KSD Model College 15


Type-2 driver
Advantage
The distinctive characteristic of type 2 jdbc drivers are that they are
typically offer better performance than the JDBC-ODBC Bridge as the
layers of communication (tiers) are less than that of Type 1 and also it
uses Native api which is Database specific.

Disadvantage
1. Native API must be installed in the Client System and hence type 2
drivers cannot be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a
portability issue.
3. If we change the Database we have to change the native api as it is
specific to a database
4. Mostly obsolete now
5. Usually not thread safe.

Asst. Prof. Jyoti Samel KSD Model College 16


Type-3 driver – Net Protocol Driver

The Network Protocol driver uses middleware (application server)


that converts JDBC calls directly or indirectly into the vendor-specific
database protocol.
mySQL Here all the database connectivity drivers are present in a single
server, hence no need of individual client-side installation.
1. Type-3 drivers are fully written in Java, hence they are portable
drivers.
2. No client side library is required because of application server that
can perform many tasks like auditing, load balancing, logging etc.
3. Network support is required on client machine.
4. Maintenance of Network Protocol driver becomes costly because
it requires database-specific coding to be done in the middle tier.
5. Switch facility to switch over from one database to another
database.

Asst. Prof. Jyoti Samel KSD Model College 17


Type-3 driver

Asst. Prof. Jyoti Samel KSD Model College 18


Type-3 driver
Advantage
1. This driver is server-based, so there is no need for any vendor database library to
be present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and
scalability.
4. The net protocol can be designed to make the client JDBC driver very small and
fast to load.
5. The type 3 driver typically provides support for features such as caching
(connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.

Disadvantage
It requires another server application to install and maintain. Traversing the
recordset may take longer, since the data comes through the backend server.

Asst. Prof. Jyoti Samel KSD Model College 19


Type-4 driver
Type-4 driver is also called native protocol driver. This driver
interact directly with database. It does not require any native
database library, that is why it is also known as Thin Driver.

Does not require any native library and Middleware server, so


no client-side or server-side installation.
It is fully written in Java language, hence they are portable
drivers.

A type 4 JDBC driver is an all Java driver which connects


directly to the database. It is implemented for a specific
database product. Today, most JDBC drivers are type 4
drivers.

Asst. Prof. Jyoti Samel KSD Model College 20


Type-4 driver

Asst. Prof. Jyoti Samel KSD Model College 21


Type-4 driver
Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are
completely written in Java to achieve platform independence and
eliminate deployment administration issues. It is most suitable for
the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers
don't have to translate database requests to ODBC or a native
connectivity interface or to pass the request on to another server,
performance is typically quite good.
3. You don’t need to install special software on the client or server.
Further, these drivers can be downloaded dynamically.

Disadvantage
1. With type 4 drivers, the user needs a different driver for each
database.

Asst. Prof. Jyoti Samel KSD Model College 22


Asst. Prof. Jyoti Samel KSD
Model College
JDBC - Steps for connecting to database

rt
ql
ge

Asst. Prof. Jyoti Samel KSD Model College 24


import java.sql.*; package
The JDBC API is a set of classes and interface. To work
with JDBC we must import

import java.sql.*;

Asst. Prof. Jyoti Samel KSD Model College 25


load and register the JDBC driver
Register the Driver
It is first an essential part to create JDBC connection. JDBC API
provides a method Class.forName() which is used to load the
driver class explicitly. For example, if we want to load a jdbc-
odbc driver then the we call it like following.

Example to register with JDBC-ODBC Driver


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

All drivers are required to register themselves at load time. The


driver itself calls.

DriverManager .getConnection();

Asst. Prof. Jyoti Samel KSD Model College 26


Create a Connection
After registering and loading the driver in step2, now we
will create a connection using getConnection() method of
DriverManager class. This method has several
overloaded methods that can be used based on the
requirement. Basically it require the database name,
username and password to establish connection. Syntax
of this method is given below.
Syntax
Connection con =
DriverManager.getConnection("jdbc:odbc:TYIT2021”,”
TYIT",”TYIT");

Asst. Prof. Jyoti Samel KSD Model College 27


Create SQL Statement
Create SQL Statement
In this step we will create statement object using
createStatement() method. It is used to execute the sql
queries and defined in Connection class.

Example to create a SQL statement


Statement s=con.createStatement();

Asst. Prof. Jyoti Samel KSD Model College 28


Execute SQL Statement
Execute SQL Statement
After creating statement, now execute using
executeQuery() method of Statement interface. This
method is used to execute SQL statements.

s.executeQuery("select * from user");

Asst. Prof. Jyoti Samel KSD Model College 29


Retrieve the result
Result are stored on ResultSet object. Retrieving the data takes more than
one line of code.

The ResultSet.next() method moves to the next row in the ResultSet, if


there are anymore rows. If there are anymore rows, it returns true. If there
were no more rows, it will return false.
You need to call next() at least one time before you can read any data.
Before the first next() call theResultSet is positioned before the first row.
You can get column data for the current row by calling some of the
getXXX() methods, where XXX is a primitive data type.

ResultSet rs=s.executeQuery("select * from user"); while(rs.next())


{
System.out.println(rs.getString(1)+" "+rs.getString(2));
}

Asst. Prof. Jyoti Samel KSD Model College 30


Close the statement and connection objects
This is the final step in any database application.

con.close();
s,.close();
Rs.close();

Asst. Prof. Jyoti Samel KSD Model College 31


Asst. Prof. Jyoti Samel KSD Model College 32
Common JDBC Components
The JDBC API provides the following interfaces and classes:

DriverManager:
This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver
using communication sub protocol. The first driver that recognizes a
certain sub protocol under JDBC will be used to establish a database
Connection.

Driver:
This interface handles the communications with the database server.
You will interact directly with Driver objects very rarely. Instead, you
use DriverManager objects, which manages objects of this type. It
also abstracts the details associated with working with Driver objects

Asst. Prof. Jyoti Samel KSD Model College 33


Common JDBC Components
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.

Statement :
You use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing
stored procedures.

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.

SQLException:
This class handles any errors that occur in a database application.

Asst. Prof. Jyoti Samel KSD Model College 34


Statement
Statement interface is used to execute normal SQL queries. You can’t pass
the parameters to SQL query at run time using this interface. This interface
is preferred over other two interfaces if you are executing a particular SQL
query only once. The performance of this interface is also very less
compared to other two interfaces. In most of time, Statement interface is
used for DDL statements like CREATE, ALTER, DROP etc. For example,

//Creating The Statement Object


  
Statement stmt = con.createStatement();
  
//Executing The Statement
  
stmt.executeUpdate ("CREATE TABLE STUDENT(ID NUMBER NOT
NULL, NAME VARCHAR)");

Asst. Prof. Jyoti Samel KSD Model College 35


PreparedStatement
PreparedStatement is used to execute dynamic or parameterized SQL queries.
PreparedStatement extends Statement interface. You can pass the parameters to SQL query at
run time using this interface. It is recommended to use PreparedStatement if you
are executing a particular SQL query multiple times. It gives better performance than
Statement interface. Because, PreparedStatement are precompiled and the query plan is
created only once irrespective of how many times you are executing that query. This will save
lots of time.
//Creating PreparedStatement object
  
PreparedStatement pstmt = con.prepareStatement("update STUDENT set NAME = ? where ID
= ?");
  
//Setting values to place holders using setter methods of PreparedStatement object
  
pstmt.setString(1, "MyName");   //Assigns "MyName" to first place holder
          
pstmt.setInt(2, 111);     //Assigns "111" to second place holder
 
//Executing PreparedStatement
 Asst. Prof. Jyoti Samel KSD Model College 36
CallableStatement
CallableStatement is used to execute the stored procedures. CallableStatement extends
PreparedStatement. Usng CallableStatement, you can pass 3 types of parameters to stored
procedures. They are : IN – used to pass the values to stored procedure, OUT – used to hold
the result returned by the stored procedure and IN OUT – acts as both IN and OUT
parameter. Before calling the stored procedure, you must register OUT parameters using
registerOutParameter() method of CallableStatement. The performance of this interface is
higher than the other two interfaces. Because, it calls the stored procedures which are already
compiled and stored in the database server.
//Creating CallableStatement object
 
CallableStatement cstmt = con.prepareCall("{call anyProcedure(?, ?, ?)}");
 //Use cstmt.setter() methods to pass IN parameters
 //Use cstmt.registerOutParameter() method to register OUT parameters
 //Executing the CallableStatement
 cstmt.execute();
 
//Use cstmt.getter() methods to retrieve the result returned by the stored procedure

Asst. Prof. Jyoti Samel KSD Model College 37


Asst. Prof. Jyoti Samel KSD Model College 38

You might also like