Unit V R2
Unit V R2
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
JDBC drivers:
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:
Play Videox
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
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:
Do You Know
o How to connect Java application with Oracle and Mysql database using
JDBC?
o What is the difference between Statement and PreparedStatement interface?
o How to print total numbers of tables and views of a database using JDBC?
o How to store and retrieve images from Oracle database using JDBC?
o How to store and retrieve files from Oracle database using JDBC?
What is API
2) JDBC Drivers
In this JDBC tutorial, we will learn four types of JDBC drivers, their advantages
and disadvantages.
In this JDBC tutorial, we will connect a simple Java program with the Oracle
database.
In this JDBC tutorial, we will connect a simple Java program with the MySQL
database.
Let's connect java application with access database with and without DSN.
7) DriverManager class
In this JDBC tutorial, we will learn what does the DriverManager class and what
are its methods.
8) Connection interface
In this JDBC tutorial, we will learn what is Connection interface and what are its
methods.
9) Statement interface
In this JDBC tutorial, we will learn what is Statement interface and what are its
methods.
In this JDBC tutorial, we will learn what is ResultSet interface and what are its
methods. Moreover, we will learn how we can make the ResultSet scrollable.
11) PreparedStatement Interface
In this JDBC tutorial, we will learn how we can get the metadata of a table.
In this JDBC tutorial, we will learn how we can get the metadata of a database.
Let's learn how to store image in the Oracle database using JDBC.
Let's see the simple example to retrieve image from the Oracle database using
JDBC.
Let's see the simple example to store file in the Oracle database using JDBC.
Let's see the simple example to retrieve file from the Oracle database using JDBC.
18) CallableStatement
Let's see the code to call stored procedures and functions using CallableStatement.
19) Transaction Management using JDBC
Let's see the simple example to use transaction management using JDBC.
JDBC Driver
1. JDBC Drivers
1. JDBC-ODBC bridge driver
2. Native-API driver
3. Network Protocol driver
4. Thin driver
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
The 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.
This is now discouraged because of thin driver.
In Java 8, the JDBC-ODBC Bridge has been removed.
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:
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:
Disadvantage:
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.
Advantage:
Disadvantages:
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:
Disadvantage:
The forName() method of Class class is used to register the driver class. This method is used to
load the driver class.
1. Class.forName("oracle.jdbc.driver.OracleDriver");
The getConnection() method of DriverManager class is used to establish connection with the da
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
The createStatement() method of Connection interface is used to create statement. The object of
responsible to execute queries with the database.
1. Statement stmt=con.createStatement();
The executeQuery() method of Statement interface is used to execute queries to the database. T
returns the object of ResultSet that can be used to get all the records of a table.
By closing connection object statement and ResultSet will be closed automatically. The close(
Connection interface is used to close the connection.
1. con.close();
Note: Since Java 7, JDBC has ability to use try-with-resources statement to
automatically close resources of type Connection, ResultSet, and Statement.
To connect java application with the oracle database, we need to follow 5 following steps. In th
we are using Oracle 10g as the database. So we need to know following information for the orac
1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver
2. Connection URL: The connection URL for the oracle10G
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database
driver, localhost is the server name on which oracle is running, we may also use IP addr
the port number and XE is the Oracle service name. You may get all these informati
tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle database
Create a Table
Before establishing connection, let's first create a table in oracle database. Following is the SQ
create a table.
1. create table emp(id number(10),name varchar2(40),age number(3));
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
}
}
download this example
The above example will fetch all the records of emp table.
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:
1. C:>set classpath=c:\folder\ojdbc14.jar;.;
Let's first create a table in the mysql database, but before creating table, we need to
create database first.
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);}
}
}
download this example
The above example will fetch all the records of emp table.
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
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 give
already registered.
2) public static synchronized void is used to deregister the given driver (drop the driv
deregisterDriver(Driver driver): list) with DriverManager. If the given driver
removed from the list, then no action is perform
method.
3) public static Connection is used to establish the connection with the specifi
getConnection(String url) throws SQLException is thrown when the corresponding D
SQLException: of the given database is not registered
DriverManager.
5) public static Driver getDriver(String Those drivers that understand the mentioned URL
url) the parameter of the method) are returned by t
provided those drivers are mentioned in the list o
drivers.
6) pubic static int getLoginTimeout() The duration of time a driver is allowed to wait
establish a connection with the database is return
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 is
wait in order to establish a connection with the da
is passed in the parameter of this method, the drive
to wait infinitely while trying to establish the conn
the database.
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
","system","oracle");
Statement stmt=con.createStatement();
ResultSet interface
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. ResultSet.CONCUR_UPDATABLE);
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 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.
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
","system","oracle");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Result
Set.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");
//getting the record of 3rd row
rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
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.
Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter ind
public void setString(int paramIndex, String sets the String value to the given parameter inde
value)
public void setFloat(int paramIndex, float sets the float value to the given parameter index
value)
public void setDouble(int paramIndex, sets the double value to the given parameter ind
double value)
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
","system","oracle");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
}
download this example
import java.sql.*;
import java.io.*;
class RS{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe
","system","oracle");
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.
Commonly used methods of ResultSetMetaData interface
Method Description
public String getTableName(int index)throws it returns the table name for the
SQLException column index.
The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Synta
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