Unit V JDBC
Unit V JDBC
Unit V JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database. It is a part of JavaSE (Java Standard Edition).
JDBC API uses JDBC drivers to connect with the database. There are four types of
We can use JDBC API to access tabular data stored in any relational database. By the
help of JDBC API, we can save, update, delete and fetch data from the database. It is
like Open Database Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017.
It is based on the X/Open SQL Call Level Interface. The java.sql package contains
classes and interfaces for JDBC API. A list of popular interfaces of JDBC API are
given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
Page 1
Object Oriented Programming Through JAVA Unit-V
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
o DriverManager class
o Blob class
o Clob class
o Types class
Before JDBC, ODBC API was the database API to connect and execute the 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).
We can use JDBC API to handle database using Java program and can perform the
following activities:
What is API
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
Page 2
Object Oriented Programming Through JAVA Unit-V
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that
you use JDBC drivers provided by the vendor of your database instead of the JDBC-
ODBC Bridge.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC
function calls.
o The ODBC driver needs to be installed on the client machine.
Page 3
Object Oriented Programming Through JAVA Unit-V
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in
java.
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.
The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. It is fully written
in java.
Page 4
Object Oriented Programming Through JAVA Unit-V
Advantage:
o No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol.
That is why it is known as thin driver. It is fully written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depend on the Database.
Page 5
Object Oriented Programming Through JAVA Unit-V
The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put
vender's Jar in the classpath, and then JDBC driver manager can detect and load the
driver automatically.
Class.forName("oracle.jdbc.driver.OracleDriver");
Page 6
Object Oriented Programming Through JAVA Unit-V
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
Statement stmt=con.createStatement();
Page 7
Object Oriented Programming Through JAVA Unit-V
Page 8
Object Oriented Programming Through JAVA Unit-V
Create a Table
Before establishing connection, let's first create a table in oracle database. Following is
the SQL query to create a table.
create table emp(id number(10),name varchar2(40),age number(3));
Page 9
Object Oriented Programming Through JAVA Unit-V
To connect java application with the Oracle database ojdbc14.jar file is required to be
loaded.
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
Firstly, search the ojdbc14.jar file then open command prompt and write:
C:>set classpath=c:\folder\ojdbc14.jar;.;
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;
Page 10
Object Oriented Programming Through JAVA Unit-V
In this example we are using MySql as the database. So we need to know following
informations for the mysql database:
Let's first create a table in the mysql database, but before creating table, we need to
create database first.
Page 11
Object Oriented Programming Through JAVA Unit-V
In this example, sonoo is the database name, root is the username and password both.
import java.sql.*;
class MysqlCon
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
The above example will fetch all the records of emp table.
Page 12
Object Oriented Programming Through JAVA Unit-V
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
2) Set classpath:
DriverManager class
The DriverManager class is the component of JDBC API and also a member of
the java.sql package. The DriverManager class acts as an interface between users and
drivers. It keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver. It contains all the
appropriate methods to register and deregister the database driver class and to create a
connection between a Java application and the database. The DriverManager class
maintains a list of Driver classes that have registered themselves by calling the method
DriverManager.registerDriver(). Note that before interacting with a Database, it is a
mandatory process to register the driver; otherwise, an exception is thrown.
Method Description
Page 13
Object Oriented Programming Through JAVA Unit-V
1) public static synchronized void is used to register the given driver with DriverM
registerDriver(Driver driver): action is performed by the method when the giv
already registered.
2) public static synchronized void is used to deregister the given driver (drop the dri
deregisterDriver(Driver driver): list) with DriverManager. If the given drive
removed from the list, then no action is perfo
method.
3) public static Connection is used to establish the connection with the speci
getConnection(String url) throws SQLException is thrown when the corresponding
SQLException: of the given database is not registered
DriverManager.
5) public static Driver getDriver(String Those drivers that understand the mentioned UR
url) the parameter of the method) are returned by
provided those drivers are mentioned in the list
drivers.
6) pubic static int getLoginTimeout() The duration of time a driver is allowed to wai
establish a connection with the database is retu
method.
7) pubic static void The method provides the time in seconds. sec m
setLoginTimeout(int sec) the parameter is the maximum time that a driver
wait in order to establish a connection with the d
is passed in the parameter of this method, the driv
to wait infinitely while trying to establish the con
the database.
Page 14
Object Oriented Programming Through JAVA Unit-V
Connection interface
4) public void commit(): saves the changes made since the previous commit/rollback
is 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.
There are some common Connection interface constant fields that are present in the
Connect interface. These fields specify the isolation level of a transaction.
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.
Let’s see the simple example of Statement interface to insert, update and delete the
record.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","s
ystem","oracle");
Statement stmt=con.createStatement();
con.close();
}}
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor
points to before the first row.
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:
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 is used to move the cursor to the specified row
row): number in the ResultSet object.
6) public boolean relative(int is used to move the cursor to the relative row
row): number in the ResultSet object, it may be positive
or negative.
7) public int getInt(int is used to return the data of specified column index
columnIndex): of the current row as int.
8) public int getInt(String is used to return the data of specified column name
columnName): of the current row as int.
Page 17
Object Oriented Programming Through JAVA Unit-V
9) public String getString(int is used to return the data of specified column index
columnIndex): of the current row as String.
10) public String is used to return the data of specified column name
getString(String of the current row as String.
columnName):
Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","s
ystem","oracle");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.
CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");
con.close();
}}
PreparedStatement interface
As you can see, we are passing parameter (?) for the values. Its value will be set by
calling the setter methods of PreparedStatement.
Page 18
Object Oriented Programming Through JAVA Unit-V
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter in
public void setString(int paramIndex, String sets the String value to the given parameter ind
value)
public void setFloat(int paramIndex, float sets the float value to the given parameter inde
value)
public void setDouble(int paramIndex, sets the double value to the given parameter in
double value)
Page 19
Object Oriented Programming Through JAVA Unit-V
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","s
ystem","oracle");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
}
download this example
Page 20
Object Oriented Programming Through JAVA Unit-V
do{
System.out.println("enter id:");
int id=Integer.parseInt(br.readLine());
System.out.println("enter name:");
String name=br.readLine();
System.out.println("enter salary:");
Page 21
Object Oriented Programming Through JAVA Unit-V
float salary=Float.parseFloat(br.readLine());
ps.setInt(1,id);
ps.setString(2,name);
ps.setFloat(3,salary);
int i=ps.executeUpdate();
System.out.println(i+" records affected");
con.close();
}}
The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name,
column type etc. , ResultSetMetaData interface is useful because it provides methods
to get metadata from the ResultSet object.
Method Description
Page 22
Object Oriented Programming Through JAVA Unit-V
The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Syn
1. public ResultSetMetaData getMetaData()throws SQLException
import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output:Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER
Page 23