Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 23

JDBC

JAVA DATABASE CONNECTIVITY


INDEX
• Introducation
• Why use JDBC?
• JDBC Drivers (4 Types)
• Which Driver should be Used?
• Class.forName()
• Connection Interface
• Java DriverManager class
• Statement interface
• ResultSet interface
INTRODUCTION
Java Database Connectivity (JDBC) is an application programming
interface (API) which allows the programmer to connect and
interact with various databases in tabular form like ORACLE, MY-
SQL, MS-ACCESS, SQL-SERVER and etc. It provides various classes,
methods to perform various operations.
• Create, Drop databases and tables.
• Insert, Delete, Update, Display, Search record from database or
table.
• JDBC API has tow major packages for all classes and interfaces
import java.sql.*;
import javax.sql.*;
• JDBC provides two types of queries SQL QUERY and SQL NON-
QUERY
Why use JDBC?
• Before JDBC, ODBC API was the database API
to connect and execute query with the
database. But, ODBC API uses ODBC driver
which is written in C language (i.e. platform
dependent and unsecured). That is why Java
has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
JDBC DRIVERS(4 TYPES)
Type 1 Driver- the JDBC-ODBC bridge :
The JDBC type 1 driver, also known as the JDBC-ODBC bridge is a database
driver implementation that the ODBC driver to connect to the database.
The driver converts JDBC method calls into ODBC function calls. The bridge
is usually used when there is no pure-Java driver available for a particular
database.
The driver is implemented in the sun.jdbc.odbc.JdbcOdbcDriver class .
The driver is platform-dependent as it makes use of ODBC which in turn
depends on native libraries of the operating system.
Advantage :
Almost any database for which ODBC driver is installed, can be accessed.
Disadvantage :
a) Performance overhead since the calls have to go through the JDBC
overhead bridge to the ODBC driver.
b) The ODBC driver needs to be installed on the client machine
c) considering the client-side software needed, this might not be suitable
for applets.
Type 2 Driver - the Native-API Driver :
The JDBC type 2 driver, also known as the Native-API driver is a database
driver implementation that uses the client-side libraries of the database.
The driver converts JDBC method calls into native calls of the database
API.
The type 2 driver is not written entirely in Java as it interfaces with non-
Java code that makes the final database calls.
A native-API partly Java technology-enabled driver converts JDBC calls into
calls on the client API for ORACLE, DB2 or other . Note that, like the bridge
driver, this style of driver requires that some binary code be loaded on
each client machine.
However the type 2 driver provides more functionality and performance
than the type 1 driver as it does not have the overhead of the additional
ODBC function calls.
Advantage:
Better performance than Type 1 since no jdbc to odbc translation is
needed
Disadvantage :
a) The vendor client library needs to be installed on the client machine.
b) Cannot be used in internet due the client side software needed
c) Not all databases give the client side library
Type 3 driver - the Network-Protocol Driver(JDBC-Net pure java):
The JDBC type 3 driver, also known as the network-protocol driver
is a database driver implementation which makes use of a middle-
tier between the calling program and the database. The middle-tier
(application server) converts JDBC calls directly or indirectly into the
vendor-specific database protocol.
Advantages:
a) 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.
b) The Middleware Server (Can be a full fledged J2EE Application
server) can provide typical middleware services like caching
(connections, query results, and so on), load balancing etc.
Disadvantages :
a) Requires database-specific coding to be done in the middle
tier.
b) An extra layer added may result in a time-bottleneck
Type 4 - the Native-Protocol Driver :
The JDBC type 4 driver, also known as the native-protocol driver is a
database driver implementation that converts JDBC calls directly
into the vendor-specific database protocol.
The type 4 driver is written completely in Java and is hence
platform independent. It is installed inside the Java Virtual Machine
of the client. It provides better performance over the type 1 and 2
drivers as it does not have the overhead of conversion of calls into
ODBC or database API calls. Unlike the type 1 and 2 drivers, it does
not need associated software to work..
Advantages :
a) These drivers don't translate the requests into db request to
ODBC or pass it to client api for the db, nor do they need a
middleware layer for request indirection. Thus the performance is
considerably improved.
b) Web application mainly used this driver.
Disadvantage:
At client side, a separate driver is needed for each database. ex-
classes12.zip (for ORACLE)
Which Driver should be Used?
• If you are accessing one type of database, such as
Oracle, Sybase, or IBM, the preferred driver type is 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 yet for your database.
• The type 1 driver is not considered a deployment-level
driver, and is typically used for development and
testing purposes only.
Two Tier
Class.forName()
• Description
• The java.lang.Class.forName(String className) method returns the Class object associated with
the class or interface with the given string name.
• Declaration
• Following is the declaration for java.lang.Class.forName() method
• Explanation
• Class.forName("X") loads the class if it not already loaded. The JVM keeps track of all the classes
that have been previously loaded. This method uses the classloader of the class that invokes it. The
"X" is the fully qualified name of the desired class.
Syntax:
public static Class.forName(String className) throws
ClassNotFoundException{…}

Example: for MS-Access


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Parameters
• className -- This is the fully qualified name of
the desired class.
• Return Value
• This method returns the Class object for the class
with the specified name.
• Exception
• LinkageError -- if the linkage fails.
• ExceptionInInitializerError -- if the initialization
provoked by this method fails.
• ClassNotFoundException -- if the class cannot be
located.
Connection Interface
• A Connection is the session between java
application and database. The Connection
interface is a factory of Statement,
PreparedStatement, and DatabaseMetaData i.e.
object of Connection can be used to get the
object of Statement and DatabaseMetaData. The
Connection interface provide many methods for
transaction management like commit(),rollback()
etc.
By default, connection commits the changes
after executing queries.
Commonly used methods of
Connection interface
• 1) public Statement createStatement(): creates a statement object
that can be used to execute SQL queries.
• 2) public Statement createStatement(int resultSetType,int
resultSetConcurrency): Creates a Statement object that will
generate ResultSet objects with the given type and concurrency.
• 3) public void setAutoCommit(boolean status): is used to set the
commit status.By default it is true.
• 4) public void commit(): saves the changes made since the previous
commit/rollback permanent.
• 5) public void rollback(): Drops all changes made since the previous
commit/rollback.
• 6) public void close(): closes the connection and Releases a JDBC
resources immediately.
• Syntax:
• Connection <obj> =
DriverManager.getConnection(<“Connection_
String with database_name”>,
[”User_Name”],[”Password”]);
• Example: for MS-Access
• Connection cn =
DriverManager.getConnection("jdbc:odbc:Driv
er=Microsoft Access Driver (*.mdb,
*.accdb);DBQ=d:/mits_jiwaji.accdb");
Java DriverManager class
• DriverManager is a static class in the Java Plaform, Standard
Edition (J2SE) and Java SE Development Kit (JDK).
• DriverManager manages the set of Java Database
Connectivity (JDBC) drivers that are available for an
application to use.
• Applications can use multiple JDBC drivers concurrently if
necessary. Each application specifies a JDBC driver by using
a Uniform Resource Locator (URL). By passing a URL for a
specific JDBC driver to the DriverManager, the application
informs the DriverManager about which type of JDBC
connection should be returned to the application.
Statement interface
• The Statement interface provides methods to execute queries with
the database. The statement interface is a factory of ResultSet i.e. it
provides factory method to get the object of ResultSet.
Commonly used methods of Statement interface
1) public ResultSet executeQuery(String sql): is used to execute
SELECT query. It returns the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified
query, it may be create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries
that may return multiple results.
4) public int[] executeBatch(): is used to execute batch of
commands.
ResultSet interface
• The object of ResultSet maintains a cursor pointing to a
particular row of data. Initially, cursor points to before the
first row.
• 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:
• Statement stmt = con.createStatement(ResultSet.TYPE_SCR
OLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
• By default, ResultSet object can be moved forward only
and it is not updatable.
Commonly used methods of ResultSet interface
• 1) public boolean next():is used to move the cursor to the one row next from the
current position.
• 2) public boolean previous():is used to move the cursor to the one row previous
from the current position.
• 3) public boolean first():is used to move the cursor to the first row in result set
object.
• 4) public boolean last():is used to move the cursor to the last row in result set
object.
• 5) public boolean absolute(int row):is used to move the cursor to the specified
row number in the ResultSet object.
• 6) public boolean relative(int row):is used to move the cursor to the relative row
number in the ResultSet object, it may be positive or negative.
• 7) public int getInt(int columnIndex):is used to return the data of specified column
index of the current row as int.
• 8) public int getInt(String columnName):is used to return the data of specified
column name of the current row as int.
• 9) public String getString(int columnIndex):is used to return the data of specified
column index of the current row as String.
• 10) public String getString(String columnName):is used to return the data of
specified column name of the current row as String.

You might also like