Unit 5
Unit 5
Applications of JDBC
JDBC enables you to create Java applications that handle the following three programming tasks:
Make a connection to a data source, such as a database.
Send database queries and update statements.
Retrieve and process the database results that were returned in response to your query.
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 –
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.
Following is the architectural diagram, which shows the location of the driver manager with respect
to the JDBC drivers and the Java application −
Two-tier Architecture
Two-tier Architecture provides direct communication between Java applications to the database. It
requires a JDBC driver that can help to communicate with the particular database.
Three-tier Architecture
In the three-tier model, commands are sent by the HTML browser to middle services i.e. Java
application which can send the commands to the particular database. The middle tier has been
written in C or C++ languages. It can also provide better performance.
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
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.
As a common driver is used in order to interact with different databases, the data
transferred through this driver is not so secured.
The ODBC bridge driver is needed to be installed in individual client machines.
Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
This driver software is built-in with JDK so no need to install separately.
It is a database independent driver.
Where oracle is the database, thin is the driver, @localhost is the IP Address where the
database is stored, 1521 is the port number, and xe is the service provider. All three parameters
are of String type and the programmer should declare them before calling the function
Here, con is a reference to the Connection interface that we used in the previous step.
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.
The most common approach to register a driver is to use Java's Class.forName() method, to
dynamically load the driver's class file into memory, which automatically registers it. This method is
preferable because it allows you to make the driver registration configurable and portable.
The following example uses Class.forName( ) to register the Oracle driver −
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
}
Approach II - DriverManager.registerDriver()
The second approach you can use to register a driver, is to use the
static DriverManager.registerDriver() method.
The following example uses registerDriver() to register the Oracle driver −
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
}
Methods of the DriverManager Class
Method Description
2) void deregisterDriver(Driver is used to deregister the given driver (drop the driver from
driver): the list) with DriverManager. If the given driver has been
removed from the list, then no action is performed by the
method.
3) public static Connection is used to establish the connection with the specified url.
getConnection(String url) throws The SQLException is thrown when the corresponding
SQLException: Driver class of the given database is not registered with the
DriverManager.
4) public static Connection is used to establish the connection with the specified url,
getConnection(String url,String username, and password. The SQLException is thrown
userName,String password) when the corresponding Driver class of the given database
throws SQLException: is not registered with the DriverManager.
5) public static Driver Those drivers that understand the mentioned URL (present
getDriver(String url) in the parameter of the method) are returned by this
method.
Connection interface
A Connection is a session between a Java application and a database. It helps to establish a connection
with the database.
The Connection interface provide many methods for transaction management like commit(), rollback
(),etc.
2) public void commit(): saves the changes made since the previous commit/rollback is permanent.
3) public void rollback(): Drops all changes made since the previous commit/rollback.
4) public void close(): closes the connection and Releases a JDBC resources immediately.
Statement interface
The Statement interface provides methods to execute queries with the database.
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.
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table.
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 int getInt(int columnIndex): is used to return the data of specified column index of the
current row as int.
7) public int getInt(String is used to return the data of specified column name of the
columnName): current row as int.
8) public String getString(int is used to return the data of specified column index of the
columnIndex): current row as String.
9) public String getString(String is used to return the data of specified column name of the
columnName): current row as String.
Steps to run jdbc Programs
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
Example:
SQL> CREATE TABLE emp (
id int,
fname varchar(255),
lname varchar(255),
);
Syntax:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
SQL> insert into emp values (1,'akshay','somwanshi');
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Example : Create Table
import java.sql.*;
public class CreateTable{
public static void main(String args[])
{
try
{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Example : Insert Row into Table
import java.sql.*;
public class InsertRow{
public static void main(String args[])
{
try
{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Example : UpdateRow from Table
import java.sql.*;
public class UpdateRow{
public static void main(String args[])
{
try
{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Example : Delete Row from Table
import java.sql.*;
public class DeleteRow{
public static void main(String args[])
{
try
{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
.
PreparedStatement
A PreparedStatement is a pre-compiled SQL statement. Prepared Statement objects have some
useful additional features than Statement objects. Instead of hard coding queries,
PreparedStatement object provides a feature to execute a parameterized query.
Advantages of PreparedStatement
When PreparedStatement is created, the SQL query is passed as a parameter. This Prepared
Statement contains a pre-compiled SQL query, so when the PreparedStatement is executed,
DBMS can just run the query instead of first compiling it.
We can use the same PreparedStatement and supply with different parameters at the time of
execution.
An important advantage of PreparedStatements is that they prevent SQL injection attacks.
Methods of PreparedStatement:
setInt(int, int): This method can be used to set integer value at the given parameter index.
setString(int, string): This method can be used to set string value at the given parameter
index.
setFloat(int, float): This method can be used to set float value at the given parameter index.
setDouble(int, double): This method can be used to set a double value at the given
parameter index.
executeUpdate(): This method can be used to create, drop, insert, update, delete etc. It
returns int type.
executeQuery(): It returns an instance of ResultSet when a select query is executed.
Example of Prepared Statement:-
Insert Values into table
import java.util.*;
import java.sql.*;
class Program4
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","123");
catch (Exception e)
{
System.out.println(e);
}
}
}
Inserting Rows into Table untill User types ‘n’
import java.util.*;
import java.sql.*;
class Program6
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","123");
Method Description
public int getColumnCount()throws SQLException it returns the total number of columns in the
ResultSet object.
public String getColumnName(int index)throws it returns the column name of the specified
SQLException column index.
public String getColumnTypeName(int it returns the column type name for the
index)throws SQLException specified index.
Example:
import java.sql.*;
class Program5{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","123");
Output:
Total columns: 3
Column Name of 1st column: ROLL
Column Type Name of 1st column: NUMBER
Column Name of 1st column: NAME
Column Type Name of 1st column: VARCHAR2
Column Name of 1st column: MARKS
Column Type Name of 1st column: NUMBER
CallableStatement
The CallableStatement interface provides methods to execute the stored procedures.
Creating a CallableStatement
You can create an object of the CallableStatement (interface) using the prepareCall() method of
the Connection interface. This method accepts a string variable representing a query to call the
stored procedure and returns a CallableStatement object.
A Callable statement can have input parameters, output parameters or both. To pass input
parameters to the procedure call you can use place holder and set values to these using the setter
methods (setInt(), setString(), setFloat()) provided by the CallableStatement interface.
Suppose you have a procedure name myProcedure in the database you can prepare a callable
statement as:
//Preparing a CallableStatement
CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}");
cstmt.setString(1, "Raghav");
cstmt.setInt(2, 3000);
cstmt.setString(3, "Hyderabad");
cstmt.execute();
Full example to call the stored procedure using JDBC
To call the stored procedure, you need to create it in the database. Here, we are assuming that stored
procedure looks like this.
create or replace procedure "MyProcedure" (roll in number, name in varchar, marks in number) is
begin
insert into students values(roll,name,marks);
end;
/
The table structure is given below:
create table students (id number(10), name varchar2(200), marks number);
Example
In this example, we are going to call the stored procedure MyProcedure that receives roll, name and
marks as the parameter and inserts it into the table students. Note that you need to create the
students table as well to run this application.
import java.sql.*;
public class Proc {
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");
System.out.println("success");
}
}