Chapter 5 JDBC Programming
Chapter 5 JDBC Programming
Topics:
1. JDBC Architecture
2. Types of JDBC Drivers
3. Introduction to major JDBC classes and interface
4. Creating Simple JDBC Application
5. Types of statement (Statement Interface, PreparedStatement, CallableStatement)
6. Exploring ResultSet Operation
7. Creating CRUD Application
Define JDBC
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.
1
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
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
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
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 (Open Database Connectivity) 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.
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:
3
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
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
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.
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.
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.
5
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
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.
Class/Interfaces Description
6
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
Class/Interfaces Description
The below Java program demonstrates how to establish a MYSQL database connection
using JDBC and execute a query.
String url
= "jdbc:mysql://localhost:3306/your_database";
// Establish connection
Connection c = DriverManager.getConnection(
url, username, password);
// Create a statement
Statement st = c.createStatement();
8
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
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.
Support for Multiple Databases: It works with popular databases like MySQL,
PostgreSQL, Oracle, etc.
In Java, the Statement interface in JDBC (Java Database Connectivity) is used to create
and execute SQL queries in Java applications. JDBC provides three types of statements to
interact with the database:
1. Statement
2. Prepared Statement
3. Callable Statement
9
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
1. Statement
A Statement object is used for general-purpose access to databases and is useful for
executing static SQL statements at runtime.
Syntax:
Statement statement = connection.createStatement();
Implementation: Once the Statement object is created, there are three ways to execute it.
Example:
// Java Program illustrating Create Statement in JDBC
import java.sql.*;
// Create a statement
Statement st = con.createStatement();
// Execute a query
String sql = "SELECT * FROM people";
ResultSet rs = st.executeQuery(sql);
// Close resources
rs.close();
st.close();
con.close();
} catch (Exception e) {
10
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
e.printStackTrace();
}
}
}
2. Prepared Statement
A PreparedStatement represents a precompiled SQL statement that can be executed
multiple times. It accepts parameterized SQL queries, with ? as placeholders for
parameters, which can be set dynamically.
Illustration:
Considering in the people database if there is a need to INSERT some values, SQL
statements such as these are used:
To do the same in Java, one may use Prepared Statements and set the values in the ?
holders, setABC() of a prepared statement is used as shown:
Implementation: Once the PreparedStatement object is created, there are three ways to
execute it:
execute(): This returns a boolean value and executes a static SQL statement that is
present in the prepared statement object.
11
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
executeUpdate(): This returns the number of rows affected by the DML statements
such as INSERT, DELETE, and more that is present in the current Prepared Statement.
Example:
// Java Program illustrating Prepared Statement in JDBC
import java.sql.*;
import java.util.Scanner;
class Geeks {
System.out.println(
"What age do you want to search?? ");
// Create a statement
PreparedStatement ps = con.prepareStatement(
"select name from world.people where age = ?");
catch (SQLException e) {
3. Callable Statement
A CallableStatement is used to execute stored procedures in the database. Stored
procedures are precompiled SQL statements that can be called with parameters. They are
useful for executing complex operations that involve multiple SQL statements.
Syntax:
CallableStatement cstmt = con.prepareCall(“{call ProcedureName(?, ?)}”);
{call ProcedureName(?, ?)}: Calls a stored procedure named ProcedureName with
placeholders ? for input parameters.
Methods to Execute:
execute(): Executes the stored procedure and returns a boolean indicating whether the
result is a ResultSet (true) or an update count (false).
executeUpdate(): Executes a stored procedure that performs an update and returns the
number of rows affected.
Example:
// Java Program illustrating
// Callable Statement in JDBC
import java.sql.*;
13
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
// Establish a connection
Connection con = DriverManager
.getConnection("jdbc:mysql:///world", "root", "12345");
// Create a CallableStatement
CallableStatement cs =
con.prepareCall("{call GetPeopleInfo()}");
// Close resources
res.close();
cs.close();
con.close();
}
// Catch block for SQL exceptions
catch (SQLException e) {
e.printStackTrace();
}
// Catch block for ClassNotFoundException
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output:
Explanation:
This Java code demonstrates how to use a CallableStatement in JDBC to execute a
stored procedure.
14
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
After executing the procedure, it runs a SELECT query to retrieve and display all
records from the people table.
Exception handling is included to manage potential SQL and class loading errors.
Java Database Connectivity is Java-based technology and that provides a standard API for
accessing databases in Java applications. The Key Component of Java Database Connectivity
is the ResultSet. JDBC driver allows developers to read and manipulate data from the
database.
The JDBC ResultSet is Object which represents the result of a SQL Query executed on a
database. It acts as a cursor to navigate through the retrieved data, manipulate data, Fetching
Specific columns and others. In this article, we will learn more about JDBC 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. And It is the part of JDBC API which is used for
interacting with relational databases. The ResultSet allows us over the rows of tables returned
by the SQL query and extract a specific column from the SQL query result.
Syntax:
try {
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM your_table");
while (rs.next()) {
// Process the result set
}
rs.close();
stmt.close();
conn.close();
}
catch (SQLException e) {
e.printStackTrace(); // Handle the exception
}
15
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
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
Method Description
16
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
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
Method Description
getInt(int columnIndex) used for Retrieves an integer from the specified column
getString(int columnIndex) used for Retrieves a string from the specified column
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
17
Chapter: 5 JDBC Programming SYBCA Sem-4 Su
ub: IPWCT
Method Description
updateBoolean(int columnIndex,
used for Updates a boolean value
boolean x)
package demo;
import java.sql.Connection;
import java.sql.DriverManager
java.sql.DriverManager;
import java.sql.PreparedStat
java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
throws Exception {
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:");
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,
20
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
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;
}
Update Record: Now we implement logic for update function. We employees details
based on their existing employee id only. It is same like inserting new record but before
that we fetch existing data then only we can able to update the data.
Fetch All Records: Now we develop logic for fetching all records from the table by
using ResultSet object. First we execute the SQL query then hold that result in ResultSet
Object. Then we iterate that data and print line by line the entire data in the table.
Delete Record by Using ID: In this function we can delete an existing employee record
by using employee ID from the Table.
Main Function: In main function of the class, We develop logic for selecting operation
from the console by using switch statement in java. Based on the selection you can
perform related database operation. Below we provide that entire code for your reference.
21
Chapter: 5 JDBC Programming SYBCA Sem-4 Su
ub: IPWCT
Output:
Showing available database operations
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.
22
Chapter: 5 JDBC Programming SYBCA Sem-4 Su
ub: IPWCT
Now enter option 4, That means you can delete an employee details by using employee ID.
Creating, reading, updating, and deleting data in a database is a common task in many
applications, and JDBC (Java Database Connectivity) is a Java API that allows you to
connect to a database and perform these operations. In this blog post, we will walk through
the steps of setting up a simple CRUD (create, read, update, delete) operation using JDBC.
Java code
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection( "jdbc:
"jdbc:mysql://localhost:3306/mydb
mysql://localhost:3306/mydb",
"username", "password");
System.out.println("Connection established.");
}
catch (Exception e) {
e.printStackTrace();
}
23
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
Java code
try {
String sql = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, "value1");
statement.setString(2, "value2");
statement.setInt(3, 123);
statement.executeUpdate();
System.out.println("Record created.");
} catch (SQLException e) {
e.printStackTrace();
}
3. Read a record
To read a record from the database, you will need to use an SQL SELECT statement and
execute it using the connection object. The result of the query will be a ResultSet object
that you can use to access the data in the record.
Java code
try {
String sql = "SELECT column1, column2, column3 FROM table_name WHERE id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1, 1);
ResultSet result = statement.executeQuery();
if (result.next()) {
String column1 = result.getString("column1");
String column2 = result.getString("column2");
int column3 = result.getInt("column3");
System.out.println("Column 1: " + column1);
System.out.println("Column 2: " + column2);
System.out.println("Column 3: " + column3);
}
} catch (SQLException e) {
e.printStackTrace();
}
24
Chapter: 5 JDBC Programming SYBCA Sem-4 Sub: IPWCT
4. Update a record
To update a record in the database, you will need to use an SQL UPDATE statement and
execute it using the connection object.
Java code
try {
String sql = "UPDATE table_name SET column1 = ?, column2 = ?, column3 = ? WHERE id =
?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, "new_value1");
statement.setString(2, "new_value2");
statement.setInt(3, 456);
statement.setInt(4, 1);
statement.executeUpdate();
System.out.println("Record updated.");
} catch (SQLException e) {
e.printStackTrace();
}
5. Delete a record
To delete a record from the database, you will need to use an SQL DELETE statement and
execute it using the connection object.
Java code
try {
String sql = "DELETE FROM table_name WHERE id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1, 1);
statement.executeUpdate();
System.out.println("Record deleted.");
} catch (SQLException e) {
e.printStackTrace();
}
25