0% found this document useful (0 votes)
104 views25 pages

Understanding JDBC Architecture and Drivers

The document provides an overview of JDBC (Java Database Connectivity), detailing its architecture, types of drivers, and the connection process. It explains the differences between JDBC and ODBC, outlines the various JDBC driver types, and describes how to use Statement and PreparedStatement objects for executing SQL queries. Additionally, it includes example code for establishing a connection to a database and performing operations on a ResultSet.

Uploaded by

bott19955
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)
104 views25 pages

Understanding JDBC Architecture and Drivers

The document provides an overview of JDBC (Java Database Connectivity), detailing its architecture, types of drivers, and the connection process. It explains the differences between JDBC and ODBC, outlines the various JDBC driver types, and describes how to use Statement and PreparedStatement objects for executing SQL queries. Additionally, it includes example code for establishing a connection to a database and performing operations on a ResultSet.

Uploaded by

bott19955
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

Unit 3:

1. JDBC Architecture:
Introduction to JDBC(Java Database Connectivity):
JDBC is an API that helps applications to communicate with databases, it allows
Java programs to connect to a database, run queries, retrieve, and manipulate data.
Because of JDBC, Java applications can easily work with different relational
databases like MySQL, Oracle, PostgreSQL, and more.

JDBC ARCHITECTURE

• Application: It can be a Java application or servlet that communicates with a data


source.
• The JDBC API: It allows Java programs to execute SQL queries and get results
from the database.
• 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
1. Two-Tier Architecture
A Java Application communicates directly with the database using a JDBC driver. It
sends queries to the database and then the result is sent back to the application. For
example, in a client/server setup, the user's system acts as a client that 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

2. Java and JDBC:


JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database, and processing the results. 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:
o JDBC-ODBC Bridge Driver
o Native Driver
o Network Protocol Driver
o Thin Driver
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.
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
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface

A list of popular classes of JDBC API are given below:


o DriverManager class
o Blob class
o Clob class
o Types class
3. JDBC VS ODBC

ODBC JDBC

1. ODBC Stands for Open Database 1. JDBC Stands for Java database
Connectivity. connectivity.

2. Introduced by SUN Micro Systems in


2. Introduced by Microsoft in 1992.
1997.

3. We can use ODBC for any language 3. We can use JDBC only for Java
like C, C++, Java etc. languages.

4. We can choose ODBC only Windows


4. We can use JDBC on any platform.
platform.

5. Mostly ODBC Driver is developed in 5. JDBC Stands for Java database


native languages like C, and C++. connectivity.

6. For Java applications it is not


6. For Java applications it is highly
recommended to use ODBC because
recommended to use JDBC because there
performance will be down due to internal
are no performance & platform dependent
conversion and applications will become
problems.
platform-dependent.

7. ODBC is procedural. 7. JDBC is object-oriented.

4. Jdbc driver model


5. JDBC driver types

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.

6. Driver Manager
What Is DriverManager?
The DriverManager class in Java is part of the [Link] package and is responsible for:
• Registering JDBC drivers
• Selecting the appropriate driver based on the connection URL
• Establishing connections to databases

Key Methods of DriverManager


Here are the most important methods used to manage drivers and connections:
• registerDriver(Driver driver): Adds a driver to the registry.
• deregisterDriver(Driver driver): Removes a driver from the registry.
• getConnection(String url): Connects using just the URL.
• getConnection(String url, String user, String password): Connects with credentials.
• getDriver(String url): Returns the driver that can handle the given URL.
• getLoginTimeout() / setLoginTimeout(int seconds): Manages connection timeout.
7. JDBC connection process
Steps to Establish a JDBC Connection
Below are the steps that explains how to connect to Database in Java:
• Step 1: Import the Packages
• Step 2: Load the drivers using the forName() method
• Step 3: Register the drivers using DriverManager
• Step 4: Establish a connection using the Connection class object
• Step 5: Create a statement
• Step 6: Execute the query
• Step 7: Close the connections

Step 1: Import the JDBC Package


First, we need to import the packages.

Step 2: Load or Register the Driver


In order to begin with, you first need to load the driver or register it before using it in the
program.
[Link]()

Here, we load the driver’s class file into memory at the runtime.
[Link](“[Link]”);
[Link]()
DriverManager is a Java inbuilt class with a static member register. Here we call the constructor
of the driver class at compile time. The following example
uses [Link]() to register the Oracle driver as shown below:
[Link](new [Link]())

Step 3: Establish a Connection


After loading the driver, establish connections as shown below as follows:
Connection con = [Link](url,user,password)
• user: Username from which your SQL command prompt can be accessed.
• password: password from which the SQL command prompt can be accessed.
• con: It is a reference to the Connection interface.
• Url: Uniform Resource Locator which is created as shown below:

Step 4: Create a Statement


Once a connection is established you can interact with the database.
Use of JDBC Statement is as follows:
Statement st = [Link]();

Step 5: Execute SQL Query


The executeQuery() method of the Statement interface is used to execute queries of retrieving
values from the database. This method returns the object of ResultSet that can be used to get all
the records of a table.

// Execute the query


ResultSet rs = [Link](query);

Step 6: Close the Connections


The close() method of the Connection interface is used to close the connection. It is shown below
as follows:
[Link]();
Java Program for Oracle Database Connection
Example: The below Java program demonstrates how to establish a JDBC Connection with an
Oracle database.
import [Link].*;
import [Link].*;
class Main {
public static void main(String a[]) {
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "system";
String pass = "12345";

Scanner k = new Scanner([Link]);


[Link]("Enter name:");
String name = [Link]();
[Link]("Enter roll no:");
int roll = [Link]();
[Link]("Enter class:");
String cls = [Link]();

String sql = "insert into student1 values('" + name + "'," + roll + ",'" + cls + "')";
Connection con = null;

try {
[Link](new [Link]());
con = [Link](url, user, pass);

Statement st = [Link]();

int m = [Link](sql);
if (m == 1)
[Link]("Inserted successfully: " + sql);
else
[Link]("Insertion failed");
[Link]();
} catch (Exception ex) {
[Link](ex);
}
}
}
8. Statement object
A Statement object is used for general-purpose access to databases and is useful for
executing static SQL statements at runtime.
Syntax:
Statement statement = [Link]();

Implementation: Once the Statement object is created, there are three ways to execute it.

• execute(String SQL): It is used to executes any SQL statements (like SELECT,


INSERT, UPDATE or DELETE). If the ResultSet object is retrieved, then it returns true
else false is returned.

• executeUpdate(String SQL): It is used to executes SQL statements (like INSERT,


UPDATE or DELETE). It returns the number of rows affected by the SQL statement.

• ResultSet executeQuery(String SQL): It is used to executes the SELECT query. It


returns a ResultSet object that contains the data retrieved by the query.

// Java Program illustrating Create Statement in JDBC


import [Link].*;

public class StatementObjDemo {


public static void main(String[] args) {
try {
// Load the driver
[Link]("[Link]");

// Establish the connection


Connection con = [Link](
"jdbc:mysql://localhost:3306/world", "root", "12345");

// Create a statement
Statement st = [Link]();

// Execute a query
String sql = "SELECT * FROM people";
ResultSet rs = [Link](sql);

// Process the results


while ([Link]()) {
[Link]("Name: " + [Link]("name") +
", Age: " + [Link]("age"));
}
// Close resources
[Link]();
[Link]();
[Link]();
} catch (Exception e) {
[Link]();
}
}
}

9. Prepared statement object


A PreparedStatement is a pre-compiled SQL statement. It is a sub interface of 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.
• 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.

Steps to use PreparedStatement


1. Create Connection to Database
Connection myCon = [Link](path,username,password)

2. Prepare Statement
PreparedStatement myStmt;
myStmt = [Link](select * from students where age> ? and name = ?);

3. Set parameter values for type and position


[Link](1,10);
[Link](2,"Chhavi");

4. Execute the Query


ResultSet myRs= [Link]();

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:
import [Link].*;
public class PreparedStatementExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String username = "root";
String password = "system";
try {
Connection con= [Link](url, username, password);
PreparedStatement pst = [Link] select * from students where
age> ? and name = ?)) {
[Link](1, 10);
[Link](2, “Chavi”);

// Executing the query


ResultSet rs = [Link]();

// Processing the result set


while ([Link]()) {
[Link]("Roll: " + [Link]("Roll_no"));
[Link]("Name: " + [Link](“Name"));
[Link]();
}
} catch (Exception e) {
[Link]();
}
}
}
10. Operation on result set

In Java, the ResultSet is the Object which is used for holding the result of a database query
typically the SQL select statement.
Syntax:
try {
Connection conn = [Link](url, username, password);
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM your_table");

while ([Link]()) {
// Process the result set
}

[Link]();
[Link]();
[Link]();
}
catch (SQLException e) {
[Link](); // 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.

1) Read Operation
Definition:
Retrieves data from the database using SELECT queries.

Example:
ResultSet rs = [Link]("SELECT * FROM table_name");
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
[Link]("ID: " + id + ", Name: " + name);
}

Methods:
• next(), previous(), first(), last(), absolute(int), relative(int)
• getInt(), getString(), getDouble(), etc.

Program:
import [Link].*;

public class ReadExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/company_db";
String user = "root";
String password = "root123";

String query = "SELECT id, name, position, salary FROM employees";

try (
Connection conn = [Link](url, user, password);
Statement stmt = [Link]();
ResultSet rs = [Link](query);
){
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
String position = [Link]("position");
double salary = [Link]("salary");

[Link]("ID: %d, Name: %s, Position: %s, Salary: %.2f%n",


id, name, position, salary);
}
} catch (SQLException e) {
[Link]();
}
}
}

2) Insert Operation
Definition:
Adds a new row to the database using ResultSet.

Example:
[Link]();
[Link]("id", 101);
[Link]("name", "Vinayak");
[Link]("salary", 50000.0);
[Link]();

Methods:
• moveToInsertRow()
• updateXXX(columnName, value)
• insertRow()

Program:
import [Link].*;

public class JDBCInsertExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/company_db";
String user = "root";
String password = "root123";

String sql = "INSERT INTO employees (id, name, position, salary) VALUES (?, ?, ?, ?)";

try {
Connection conn = [Link](url, user, password);
PreparedStatement pstmt = [Link](sql);
}
// Set values for the placeholders
[Link](1, 101);
[Link](2, "Vinayak");
[Link](3, "Developer");
[Link](4, 55000.0);

// Execute the insert


int rowsInserted = [Link]();

if (rowsInserted > 0) {
[Link]("A new employee was inserted successfully!");
}
} catch (SQLException e) {
[Link]();
}
}
}

3) Update Operation
Definition:
Modifies existing data in the database.

Example:
[Link](2); // Move to second row
[Link]("name", "Updated Name");
[Link]("salary", 60000.0);
[Link]();

Methods:
• absolute(int row)
• updateXXX(columnName, value)
• updateRow()

Program:
import [Link].*;

public class JDBCUpdateExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/jdbc_db";
String user = "root";
String password = "password";

String newCity = "Noida";


String targetEmail = "gaurav@[Link]";

try {
// Load JDBC driver
[Link]("[Link]");

// Establish connection and prepare statement


try (
Connection con = [Link](url, user, password);
PreparedStatement ps = [Link](
"UPDATE register SET city = ? WHERE email = ?")
){
// Set parameters
[Link](1, newCity);
[Link](2, targetEmail);

// Execute update
int rowsAffected = [Link]();

// Output result
if (rowsAffected > 0) {
[Link]("Update successful!");
} else {
[Link]("No matching record found.");
}
}
} catch (ClassNotFoundException | SQLException e) {
[Link]();
}
}
}

4) Delete Operation
Definition:
Removes a row from the database.

Example:
[Link](3); // Move to third row
[Link]();

Methods:
• absolute(int row)
• deleteRow()

Program:
import [Link].*;

public class JDBCDeleteExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/jdbc_db";
String user = "root";
String password = "password";

String targetEmail = "gaurav@[Link]";


try {
// Load JDBC driver
[Link]("[Link]");

// Establish connection and prepare statement


try (
Connection con = [Link](url, user, password);
PreparedStatement ps = [Link](
"DELETE FROM register WHERE email = ?")
){
// Set parameter
[Link](1, targetEmail);

// Execute delete
int rowsDeleted = [Link]();

// Output result
if (rowsDeleted > 0) {
[Link]("Record deleted successfully!");
} else {
[Link]("No matching record found.");
}
}
} catch (ClassNotFoundException | SQLException e) {
[Link]();
}
}
}

11. Transaction Processing


Transaction processing in JDBC (Java Database Connectivity) is a mechanism to ensure that a
group of database operations is executed as a single unit, maintaining the ACID (Atomicity,
Consistency, Isolation, Durability) properties. Here's a concise explanation:

Key Concepts of Transactions in JDBC:


1. Atomicity: All operations in a transaction are completed successfully, or none are
applied.
2. Consistency: Ensures the database remains in a valid state before and after the
transaction.
3. Isolation: Transactions are executed independently without interference.
4. Durability: Once a transaction is committed, changes are permanent.

Steps to Implement Transaction Processing in JDBC:


1. Disable Auto-Commit: By default, JDBC commits each SQL statement automatically.
Disable it using:
2. Copy the [Link](false);
3. Execute SQL Statements: Perform multiple SQL operations as part of the transaction.
4. Commit or Rollback:
o Use [Link]() to save changes if all operations succeed.
o Use [Link]() to undo changes if any operation fails.

Example:
import [Link];
import [Link];
import [Link];
import [Link];

public class TransactionExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";

try (Connection connection = [Link](url, user, password)) {


[Link](false); // Disable auto-commit

String sql1 = "INSERT INTO accounts (id, balance) VALUES (?, ?)";
String sql2 = "UPDATE accounts SET balance = balance - ? WHERE id = ?";

try (PreparedStatement stmt1 = [Link](sql1);


PreparedStatement stmt2 = [Link](sql2)) {

// First operation
[Link](1, 1);
[Link](2, 1000.0);
[Link]();

// Second operation
[Link](1, 500.0);
[Link](2, 1);
[Link]();

[Link](); // Commit transaction


[Link]("Transaction committed successfully.");
} catch (SQLException e) {
[Link](); // Rollback transaction on failure
[Link]("Transaction rolled back due to error: " + [Link]());
}
} catch (SQLException e) {
[Link]();
}
}
}

12. Metadata
DatabaseMetaData is an interface in Java Programming, and it is part of JDBC also. It provides
methods for getting metadata information about the database. It provides metadata about the
database like its structure, capabilities, and other properties of the database. The metadata refers
to data about the data of database with the help of JDBC. By using DatabaseMetaData, we can
perform different tasks.
• Retrieving information about database products like database name, version of the
database, driver version of the database, and other properties.
• And we can get information about tables, columns, primary keys, foreign keys, and other
things.
• And it can determine SQL syntax supported by the database.
• Also, DatabaseMetaData provides information about database objects.
We can obtain metadata from the connection object:
DatabaseMetaData metaData = [Link]();

Example:
import [Link];
import [Link];
import [Link];
import [Link];

public class RetrieveDataExample {


public static void main(String[] args) {
try {
// load MySQL JDBC driver class
[Link]("[Link]");
Connection con = [Link]("jdbc:mysql://localhost:3306/books",
"root", "password");

// Retrieve metadata about the database


DatabaseMetaData metaData = [Link]();

// Print the name of the database product


[Link]("\n\tDatabase Product Name: " +
[Link]());

// Close the database connection


[Link]();
} catch (ClassNotFoundException | SQLException e)
{
// handle exceptions that will occur during the process
[Link]("Exception is " + [Link]());
}
}
}

13. Resultset Metadata


In JDBC, ResultSetMetaData is an interface that provides information about the types and
properties of the columns in a ResultSet object. It is particularly useful when you need to
dynamically retrieve metadata about the result set, such as column names, types, and other
properties.
Key Features of ResultSetMetaData
1. Column Information: Retrieve details like column name, type, size, and more.
2. Dynamic Queries: Useful when the structure of the result set is not known beforehand.
3. Database Metadata: Helps in understanding the schema of the database.
Steps to Use ResultSetMetaData
1. Execute a query using Statement or PreparedStatement to get a ResultSet.
2. Call the getMetaData() method on the ResultSet to obtain a ResultSetMetaData object.
3. Use the methods of ResultSetMetaData to retrieve metadata about the columns.

Example Code
import [Link].*;

public class ResultSetMetaDataExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";

try (Connection connection = [Link](url, user, password);


Statement statement = [Link]();
ResultSet resultSet = [Link]("SELECT * FROM your_table")) {

// Get ResultSetMetaData
ResultSetMetaData metaData = [Link]();

// Retrieve column count


int columnCount = [Link]();
[Link]("Number of Columns: " + columnCount);

// Print column details


for (int i = 1; i <= columnCount; i++) {
[Link]("Column " + i + ":");
[Link](" Name: " + [Link](i));
[Link](" Type: " + [Link](i));
[Link](" Size: " + [Link](i));
}

} catch (SQLException e) {
[Link]();
}
}
}

14. Data types


In JDBC (Java Database Connectivity), data types are used to map SQL data types to Java data
types, enabling seamless interaction between Java applications and databases. Here's an overview
of commonly used JDBC data types:
1. SQL to Java Data Type Mapping
JDBC provides mappings between SQL data types and Java data types. Below are some
examples:
SQL Data Type Java Data Type

CHAR, VARCHAR String

II NTEGER, SMALLINT int

BIGINT long

DECIMAL, NUMERIC [Link]

FLOAT, REAL float

DOUBLE double

DATE [Link]

TIME [Link]

TIMESTAMP [Link]

BLOB [Link]

CLOB [Link]

BOOLEAN boolean

You might also like