0% found this document useful (0 votes)
23 views

JDBC Driver Types

The document discusses the different types of JDBC drivers including JDBC-ODBC bridge driver, native-API driver, network protocol driver, and thin driver. It also explains the steps to connect a Java application to a database using JDBC including registering the driver class, creating a connection, creating a statement, executing queries, and closing the connection.

Uploaded by

2201020440
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

JDBC Driver Types

The document discusses the different types of JDBC drivers including JDBC-ODBC bridge driver, native-API driver, network protocol driver, and thin driver. It also explains the steps to connect a Java application to a database using JDBC including registering the driver class, creating a connection, creating a statement, executing queries, and closing the connection.

Uploaded by

2201020440
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Types of JDBC Driver

By
Dr. Debendra Muduli
Assistant Professor
CGU, Odisha
Types of JDBC Drivers
• JDBC Driver is a software component that enables java application to
interact with the database.
There are 4 types of JDBC drivers:
• JDBC-ODBC bridge driver
• Native-API driver (partially java driver)
• Network Protocol driver (fully java driver)
• Thin driver (fully java driver)
Types of JDBC Drivers
• JDBC-ODBC bridge driver
• 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.
Types of JDBC Drivers
• 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:
• easy to use.
• can be easily connected to any database.
• Disadvantages:
• Performance degraded because JDBC method call is converted into
the ODBC function calls.
• The ODBC driver needs to be installed on the client machine.
Types of JDBC Drivers
• 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.
Types of JDBC Drivers

• Advantage:
• performance upgraded than JDBC-ODBC bridge driver.
• Disadvantage:
• The Native driver needs to be installed on the each client machine.
• The Vendor client library needs to be installed on client machine.
Types of JDBC Drivers
• Network Protocol driver
• 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.
Types of JDBC Drivers
• Advantage:
• No client side library is required because of application server that
can perform many tasks like auditing, load balancing, logging etc.
• Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in the middle tier.
• Maintenance of Network Protocol driver becomes costly because it
requires database-specific coding to be done in the middle tier.
Types of JDBC Drivers
• 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.
Types of JDBC Drivers
• Advantage:
• Better performance than all other drivers.
• No software is required at client side or server side.
• Disadvantage:
• Drivers depend on the Database.
Java Database Connectivity with 5 Steps
• There are 5 steps to connect any java application with the database
using JDBC. These steps are as follows:
• Register the Driver class
• Create connection
• Create statement
• Execute queries
• Close connection
Java Database Connectivity with 5 Steps
• Register the driver class
• The forName() method of Class class is used to register the driver
class. This method is used to dynamically load the driver class.
• Class.forName("oracle.jdbc.driver.OracleDriver");
Java Database Connectivity with 5 Steps
• Create the connection object
• The getConnection() method of DriverManager class is used to establish
connection with the database.
• Example to establish connection with the Oracle database
• Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
Java Database Connectivity with 5 Steps
• Create the Statement object
• The createStatement() method of Connection interface is used to create
statement. The object of statement is responsible to execute queries with
the database.
• Statement stmt=con.createStatement();
Java Database Connectivity with 5 Steps
• Execute the query
• The executeQuery() method of Statement interface is used to execute
queries to the database. This method returns the object of ResultSet that
can be used to get all the records of a table.
• ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Java Database Connectivity with 5 Steps
• Close the connection object
By closing connection object statement and ResultSet will be closed
automatically. The close() method of Connection interface is used to close the
connection.
con.close();
Java Database Connectivity with 5 Steps
• Close the connection object
By closing connection object statement and ResultSet will be closed
automatically. The close() method of Connection interface is used to close the
connection.
con.close();
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:
• The important methods of Statement interface are as follows:
• public ResultSet executeQuery(String sql): is used to execute SELECT query.
It returns the object of ResultSet.
• public int executeUpdate(String sql): is used to execute specified query, it
may be create, drop, insert, update, delete etc.
• public boolean execute(String sql): is used to execute queries that may
return multiple results.
• public int[] executeBatch(): is used to execute batch of commands.
Statement interface
• 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();
• //stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
• //int result=stmt.executeUpdate("update emp765 set name=‘Sekhar',salary=10000 where
id=33");
• int result=stmt.executeUpdate("delete from emp765 where id=33");
• System.out.println(result+" records affected");
• 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:

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CO


NCUR_UPDATABLE);
ResultSet interface
• 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.
ResultSet interface
• 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,ResultSet.CONCUR_UPDATABLE);
• ResultSet rs=stmt.executeQuery("select * from emp");
• //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
• The PreparedStatement interface is a subinterface of Statement. It is
used to execute parameterized query.

• Let's see the example of parameterized query:

• String sql="insert into emp values(?,?,?)";


• As you can see, we are passing parameter (?) for the values. Its value
will be set by calling the setter methods of PreparedStatement.
Methods of PreparedStatement interface
Method Description

public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.

public void setString(int paramIndex, String value) sets the String value to the given parameter index.

public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.

public void setDouble(int paramIndex, double value) sets the double value to the given parameter index.

public int executeUpdate() executes the query. It is used for create, drop,
insert, update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an instance of


ResultSet.
Example of PreparedStatement interface that inserts the record

• First of all create table as given below:


• create table emp(id number(10),name varchar2(50));
Example of PreparedStatement interface that inserts the record
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");
PreparedStatement stmt=con.prepareStatement("insert into emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e){ System.out.println(e);}
} }
Java CallableStatement Interface
• CallableStatement interface is used to call the stored procedures and
functions.

• We can have business logic on the database by the use of stored


procedures and functions that will make the performance better
because these are precompiled.

• Suppose you need the get the age of the employee based on the date
of birth, you may create a function that receives date as the input and
returns age of the employee as the output.
What is the difference between stored
procedures and functions.
Stored Procedure Function

is used to perform business logic. is used to perform calculation.

must not have the return type. must have the return type.
may return 0 or more values. may return only one values.
We can call functions from the procedure. Procedure cannot be called from function.

Procedure supports input and output Function supports only input parameter.
parameters.

Exception handling using try/catch block can be Exception handling using try/catch can't be used
used in stored procedures. in user defined functions.
Java CallableStatement Interface

• The prepareCall() method of Connection interface returns the instance of


CallableStatement. Syntax is given below:
• public CallableStatement prepareCall("{ call procedurename(?,?...?)}");
• The example to get the instance of CallableStatement is given below:
• CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");
• It calls the procedure myprocedure that receives 2 arguments.
Java CallableStatement Interface
• 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 “insertEmployee"
• (id IN NUMBER,
• name IN VARCHAR2)
• As
• Begin
• insert into employee values(id,name);
• end;
•/
• The table structure is given below:
• create table employee(id number(10), name varchar2(200));
Java CallableStatement Interface
• In this example, we are going to call the stored procedure INSERTR that receives id and name as the
parameter and inserts it into the table employee.
• 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","oracl
e");
• CallableStatement stmt=con.prepareCall("{call insertEmployee(?,?)}");
• stmt.setInt(1,1050);
• stmt.setString(2,“Deb");
• stmt.execute();

• System.out.println("success");
• }
• }
Example to call the function using JDBC
• In this example, we are calling the sum4 function that receives two
input and returns the sum of the given number. Here, we have used
the registerOutParameter method of CallableStatement interface,
that registers the output parameter with its corresponding type. It
provides information to the CallableStatement about the type of
result being displayed.
Example to call the function using JDBC
• In this example, we are calling the sum4 function that receives two input and
returns the sum of the given number. Here, we have used the
registerOutParameter method of CallableStatement interface, that registers the
output parameter with its corresponding type. It provides information to the
CallableStatement about the type of result being displayed.
• Let's create the simple function in the database first.
• create or replace function sum4 (n1 in number,n2 in number)
• return number
• is
• temp number(8);
• begin
• temp :=n1+n2;
• return temp;
• end;
• /
Example to call the function using JDBC
• Syntax
• Following is the syntax of creating a function in a(MySQL) database:
• CREATE FUNCTION Function_Name(input_arguments) RETURNS
output_parameter
• BEGIN
• declare variables;
• statements . . . . . . . . . .
• return data_type;
• END
Example to call the function using JDBC
• Suppose we have a table named Emp in the database with the
following content:

• +--------+------------+----------------+
• | Name | DOB | Location |
• +--------+------------+----------------+
• | Amit | 1970-01-08 | Hyderabad |
• | Sumith | 1970-01-08 | Vishakhapatnam |
• | Sudha | 1970-01-05 | Vijayawada |
• +--------+------------+----------------+
Example to call the function using JDBC
• Suppose we have a table named EMP in the database with the
following content:

• +--------+------------+----------------+
• | Name | DOB | Location |
• +--------+------------+----------------+
• | Amit | 1970-01-08 | Hyderabad |
• | Sumith | 1970-01-08 | Vishakhapatnam |
• | Sudha | 1970-01-05 | Vijayawada |
• +--------+------------+----------------+
Example to call the function using JDBC
• Here, we are creating a function named getDob() which accepts the
name of the employee, retrieves and returns the value of DOB
column(s).
• CREATE FUNCTION getDob(emp_name VARCHAR(50)) RETURNS DATE
• BEGIN
• declare dateOfBirth DATE;
• select DOB into dateOfBirth from EMP where Name = emp_name;
• return dateOfBirth;
• END
Example to call the function using JDBC
• Calling a function using JDBC
• You can call a function using CallableStatement object just like stored
procedures, to call a function using JDBC program you need to.
• Connect to the database.
• Create a PreparedStatement object and to its constructor pass the
function call in String format.
• Set values to the place holders.
• Execute the Callable statement.
Example to call the function using JDBC
• Following is the query to call a function from JDBC:

{? = call getDob(?)}
• As you observe the query contains place holders (?) just like prepared
and callable statements.

• In the above query the first place holder represents the return value
of the function and the second placeholder represents the input
parameter.
Example to call the function using JDBC
• You need to register the place holder which represents return value,
as an output parameter using the registerOutParameter() method(of
the CallableStatement interface). To this method you need to pass an
integer value representing the position of the place holder and, an
integer variable representing the sql type (of the parameter)

• Set the value to the input parameter using the setString() method.
(since getDoc() function accepts a value of VARCHAR type).
Example to call the function using JDBC
• import java.sql.CallableStatement;
• import java.sql.Connection;
• import java.sql.DriverManager;
• import java.sql.SQLException;
• import java.sql.Types;
• public class CallingFunctionsUsingCallable2 { OutPut:
• public static void main(String args[]) throws SQLException { Connection established......
DriverManager.registerDriver(new com.mysql.jdbc.Driver()); Date of birth: 1970-01-08
• String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
• Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
• System.out.println("Connection established......");
• CallableStatement cstmt = con.prepareCall("{? = call getDob(?)}");
• cstmt.registerOutParameter(1, Types.DATE);
• cstmt.setString(2, "Amit");
• cstmt.execute();
• System.out.print("Date of birth: "+cstmt.getDate(1));
• }
• }
Thank you

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy