Structure of JDBC Driver: JDBC Drivers JDBC Apis 4 Types of JDBC Drivers
Structure of JDBC Driver: JDBC Drivers JDBC Apis 4 Types of JDBC Drivers
how a client can access and interact with any kind of tabular data, especially a relational database. JDBC Drivers uses JDBC
APIs which was developed by Sun Microsystem, but now this is a part of Oracle. There are 4 types of JDBC drivers. It is part
of the Java Standard Edition platform, from Oracle Corporation. It acts as a middle-layer interface between Java applications
and databases.
The JDBC classes are contained in the Java Package java.sql and javax.sql.
JDBC helps you to write Java applications that manage these three programming activities:
1. Connect to a data source, like a database.
2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to your query
Structure of JDBC Driver
The above JDBC Driver structure illustrates the architecture of JDBC driver, where an application interacts with the JDBC API.
The API communicates with the JDBC Driver Manager, which manages different database drivers e.g. SQL server, Oracle to
establish database connectivity.
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine rather than the server) that translate requests from Java
programs into a protocol understood by the DBMS. These drivers are software components that implement the interfaces in
the JDBC API, allowing Java applications to interact with a database. Sun Microsystems (now Oracle) defines four types of
JDBC drivers, which are outlined below:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver
1. JDBC-ODBC Bridge Driver – 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.
Advantages
This driver software is built-in with JDK so no need to install separately.
It is a database independent driver.
Disadvantages
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.
2. Native-API Driver – Type 2 Driver ( Partially Java Driver)
The Native API driver uses the client -side libraries of the database. This driver converts JDBC method calls into native calls of
the database API. In order to interact with different database, this driver needs their local API, that’s why data transfer is much
more secure as compared to type-1 driver. This driver is not fully written in Java that is why it is also called Partially Java
driver.
Advantage
Native-API driver gives better performance than JDBC-ODBC bridge driver.
More secure compared to the type-1 driver.
Disadvantages
Driver needs to be installed separately in individual client machines
The Vendor client library needs to be installed on client machine.
Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
It is a database dependent driver.
3. Network Protocol Driver – Type 3 Driver (Fully Java Driver)
The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the
vendor-specific database protocol. Here all the database connectivity drivers are present in a single server, hence no need of
individual client-side installation.
Advantages
Type-3 drivers are fully written in Java, hence they are portable drivers.
No client side library is required because of application server that can perform many tasks like auditing, load balancing,
logging etc.
Switch facility to switch over from one database to another database.
Disadvantages
Network support is required on client machine.
Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the
middle tier.
4. Thin Driver – Type 4 Driver (Fully Java Driver)
Type-4 driver is also called native protocol driver. This driver interact directly with database. It does not require any native
database library, that is why it is also known as Thin Driver.
Advantages
Does not require any native library and Middleware server, so no client-side or server-side installation.
It is fully written in Java language, hence they are portable drivers.
Disadvantage
If the database changes, a new driver may be needed.
Which Driver to use When?
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is type-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.
JDBC (Java Database Connectivity)
JDBC (Java Database Connectivity) is an API in Java that enables applications to interact with databases. It allows a Java
program to connect to a database, execute queries, and retrieve and manipulate data. By providing a standard interface,
JDBC ensures that Java applications can work with different relational databases like MySQL, Oracle, PostgreSQL, and more.
JDBC Architecture
Explanation:
Application: It is a Java applet or a servlet that communicates with a data source.
The JDBC API: It allows Java programs to execute SQL queries and retrieve results. Key interfaces include Driver,
ResultSet, RowSet, PreparedStatement, and Connection. Important classes include DriverManager, Types, Blob, and Clob.
DriverManager: It plays an important role in the JDBC architecture. It uses some database-specific drivers to effectively
connect enterprise applications to databases.
JDBC drivers: These drivers handle interactions between the application and the database.
The JDBC architecture consists of two-tier and three-tier processing models to access a database. They are as described
below:
1. Two-Tier Architecture
A Java Application communicates directly with the database using a JDBC driver. Queries are sent to the database, and
results are returned directly to the application. In a client/server setup, the user’s machine (client) communicates with a remote
database server.
Structure:
Client Application (Java) -> JDBC Driver -> Database
2. Three-Tier Architecture
In this, user queries are sent to a middle-tier services, which interacts with the database. The database results are processed
by the middle tier and then sent back to the user.
Structure:
Client Application -> Application Server -> JDBC Driver -> Database
JDBC Components
There are generally 4 main components of JDBC through which it can interact with a database. They are as mentioned
below:
1. JDBC API
It provides various methods and interfaces for easy communication with the database. It includes two key packages
java.sql: This package, is the part of Java Standard Edition (Java SE) , which contains the core interfaces and classes for
accessing and processing data in relational databases. It also provides essential functionalities like establishing
connections, executing queries, and handling result sets
javax.sql: This package is the part of Java Enterprise Edition (Java EE) , which extends the capabilities of java.sql by
offering additional features like connection pooling, statement pooling, and data source management.
It also provides a standard to connect a database to a client application.
2. JDBC Driver Manager
Driver manager is responsible for loading the correct database-specific driver to establish a connection with the database. It
manages the available drivers and ensures the right one is used to process user requests and interact with the database.
3. JDBC Test Suite
It is used to test the operation(such as insertion, deletion, updating) being performed by JDBC Drivers.
4. JDBC Drivers
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:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver (partially java driver)
3. Type-3 driver or Network Protocol driver (fully java driver)
4. Type-4 driver or Thin driver (fully java driver) – It is deprecated and no longer supported since Java 8. Instead modern
drivers like the Type – 4 driver are widely used.
JDBC Classes and Interfaces
Class/Interfaces Description
PreparedStatement Precompiled SQL statement, used for dynamic queries with parameters.
ResultSet Represents the result set of a query, allowing navigation through the rows.
// Create a statement
Statement st = c.createStatement();
Note: When the program runs successfully, a new record is added to the students table as shown below:
Key Features
Platform Independence: It enables database operations across different platforms.
Standard API: It provides a uniform interface for various databases.
Support for Multiple Databases: It works with popular databases like MySQL, PostgreSQL, Oracle, etc.
Extensibility: It offers features like batch processing, connection pooling, and transaction management.
In Java, the DriverManager class, part of the JDBC API, manages the set of available JDBC drivers and facilitates establishing
database connections by interacting with the appropriate driver for a given database URL.
Here's a more detailed explanation:
Purpose: The DriverManager acts as an interface between your Java application and the various JDBC drivers, allowing your
application to connect to different databases without needing to know the specifics of each driver.
Functionality:
o Driver Management: It maintains a list of registered JDBC drivers.
o Connection Handling: When a connection is requested, the DriverManager iterates through the registered drivers and asks them
to attempt to connect to the target database URL, until a successful connection is established.
o Driver Registration: You can register JDBC drivers using DriverManager.registerDriver(Driver driver).
o Connection Retrieval: You can obtain a database connection using DriverManager.getConnection(String url, String user, String
password).
Example:
import java.sql.*;
try {
// Load the JDBC driver (example for MySQL)
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish a connection
Connection connection = DriverManager.getConnection(url, user, password);
if (connection != null) {
System.out.println("Connected to the database!");
// Perform database operations here
connection.close(); // Close the connection
} else {
System.out.println("Failed to connect to the database!");
}
} catch (ClassNotFoundException e) {
System.out.println("JDBC driver not found: " + e.getMessage());
} catch (SQLException e) {
System.out.println("SQL Exception: " + e.getMessage());
}
}
}
while (rs.next()) {
// Process the result set
}
rs.close();
stmt.close();
conn.close();
}
catch (SQLException e) {
e.printStackTrace(); // Handle the exception
}
Common Operations with ResultSet:
Fetching data from database: We can fetch data from the database based on the requirements by using conditional statements.
Navigating the ResultSet: We can able navigating the ResultSet by using methods like next(), previous(), first(), and last().
Getting column values: We can fetch column values with specific conditions or without conditions.
Closing the result: Once database operations are completed we need close the connections related to database here we close the ResultSet
connection. By using close method.
Types of ResultSet
There are three different characteristics by which ResultSet types are differentiated
1. Scrollability: Determines whether you can move back and forth in the ResultSet
TYPE_FORWARD_ONLY: Can only move forward through the rows
TYPE_SCROLL_INSENSITIVE: Can move forward and backward but changes are not reflect ResultSet
TYPE_SCROLL_SENSITIVE: Can move forward and backward but changes are affect the ResultSet
2. Concurrency: Determines whether you can update the ResultSet
CONCUR_READ_ONLY: Can only read data
CONCUR_UPDATABLE: Allows updates to the ResultSet
3. Holdability: Determines what happens to the ResultSet when a Transaction is committed.
HOLD_CURSORS_OVER_COMMIT: The ResultSet remains open after a commit
CLOSE_CURSORS_AT_COMMIT: The ResultSet closes after a commit
Category of Methods in Result Set
We have different types of Methods are available based on their functionality below we listed them for you reference.
i). Navigating a ResultSet:
Basically these methods are allow is to navigating through the ResultSet and we can navigate in different ways, Below We provide those
methods to navigate in the ResultSet.
Method Description
relative(int rows) used for Moves forward or backward by the specified number of rows
beforeFirst() used for Positions the cursor before the first row
afterLast() used for Positions the cursor after the last row
getInt(int columnIndex) used for Retrieves an integer from the specified column
getString(int columnIndex) used for Retrieves a string from the specified column
Method Description
getDouble(int columnIndex) used for Retrieves a double from the specified column
getBoolean(int columnIndex) used for Retrieves true or false from the specified column
updateInt(int columnIndex, int x) used for Updates an integer value in the specified column
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
PreparedStatement preparedStatement
= connection.prepareStatement(query);
preparedStatement.setString(1, name);
preparedStatement.setDouble(2, salary);
preparedStatement.executeUpdate();
String query
= "UPDATE employees SET name = ?, salary = ? WHERE id = ?";
PreparedStatement preparedStatement
= connection.prepareStatement(query);
preparedStatement.setString(1, name);
preparedStatement.setDouble(2, salary);
preparedStatement.setInt(3, id);
preparedStatement.executeUpdate();
}
}
System.out.println("Select an operation:");
System.out.println("1. Insert");
System.out.println("2. Update");
System.out.println("3. Retrieve");
System.out.println("4. Delete");
switch (choice) {
case 1:
System.out.println("Enter name:");
String nameToInsert = scanner.next();
System.out.println("Enter salary:");
double salaryToInsert = scanner.nextDouble();
insertRecord(connection, nameToInsert,
salaryToInsert);
break;
case 2:
System.out.println("Enter ID to update:");
int idToUpdate = scanner.nextInt();
System.out.println("Enter new name:");
String nameToUpdate = scanner.next();
System.out.println("Enter new salary:");
double salaryToUpdate
= scanner.nextDouble();
updateRecord(connection, idToUpdate,
nameToUpdate, salaryToUpdate);
break;
case 3:
retrieveRecords(connection);
break;
case 4:
System.out.println("Enter ID to delete:");
int idToDelete = scanner.nextInt();
deleteRecord(connection, idToDelete);
break;
default:
System.out.println("Invalid choice.");
break;
}
Now enter option 1, That means you can ready to insert data into database.
Now enter option 2, That means you can ready to update employee data by employee ID
Now enter option 3, That means you can fetch all data from table.
Now enter option 4, That means you can delete an employee details by using employee ID.
JDBC API
JDBC API is mainly divided into two package. Each when we are using JDBC, we have to import these packages to
use classes and interfaces in our application.
1. java.sql
2. javax.sql
java.sql package
This package include classes and interface to perform almost all JDBC operation such as creating and executing SQL
Queries.
classes/interface Description
This package is also known as JDBC extension API. It provides classes and interface to access server-side data.
classes/interface Description
Java Database Connectivity (JDBC) serves as the backbone for Java applications when interacting with databases.
While establishing connections and executing queries, we developers often encounter SQLExceptions, which are
inevitable in the real world. Handling those exceptions is crucial in the development of applications. Now let's
understand more about SQL Exception.
Understanding SQL Exception
Exception is a type of condition when a program encounters a problem in execution and quits with a problematic error
message. In JDBC, when the program has trouble with a data source, it throws SQLException.
Note: An SQLException can occur in the JDBC Driver or inside the database.
SQL Exception methods in Java:
METHOD NAME DESCRIPTION
Once the server gets connected then the query gets executed.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// create a PreparedStatement
preparedStatement = connection.prepareStatement(sql);
// execute the query (this will throw an SQLException in case of an error)
preparedStatement.executeQuery();
} catch (SQLException | ClassNotFoundException e) {
// handle the SQL exception
handleSQLException(e);
} finally {
// close the resources in the finally block
try {
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
handleSQLException(e);
}
}
}
e.printStackTrace();
}
}
Note: To load the JDBC Driver, first connect to the database (SQL) and fetch that link to establish the connection.
Output:
The Output of the above code will intentionally create SQL Exception error since there is no non-existence table in the database. This co
try {
// Connecting to the server and database
con = DriverManager.getConnection(dburl, dbuser, dbpass);
// Initialize Statement
stmt = con.createStatement();
// SQL Query
String query = "SELECT * FROM ITEM";
There are 5 steps to connect any java application with the database using JDBC. These steps are as follows: