Understanding JDBC in Java Programming
Understanding JDBC in Java Programming
Engineering
Project based learning using Java(B22EHS526)
BY: Prof. DARSHAN L M
The concept of JDBC
Introduction:
• JDBC (Java Database Connectivity) is a Java API that enables Java applications to interact with databases.
• It provides a standard interface for connecting to a wide range of relational databases, executing SQL
queries, and retrieving results.
• The Extension API [Link]: It provides the API for server-side data source access and processing
from Java.
• This package provides services for Java EE such as DataSource and RowSet. The DataSource
interface is an alternative to DriverManager for establishing a connection with a data source.
• JDBC extension API also provides extension services such as connection pooling, using XA enabled
connection for distributed transactions etc.
The 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
• JDBC API: This provides the application-to-JDBC Manager connection.
• JDBC Driver API: This supports the JDBC Manager-to Driver Connection.
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. It is capable of
supporting multiple concurrent drivers connected to multiple heterogeneous databases.
• API: JDBC is an API in Java (part of [Link] and [Link] packages) that provides methods to connect
to databases and execute SQL operations.
• Database Independence: JDBC allows applications to interact with different databases (e.g., MySQL,
Oracle, PostgreSQL) without needing to change the application code much.
• Drivers: JDBC uses drivers to communicate with different databases. These are vendor-specific
implementations of the JDBC interface.
• SQL Execution: It allows you to send SQL commands like SELECT, INSERT, UPDATE, and DELETE
from Java code to a database.
Main JDBC Components:
1. DriverManager:
Manages database drivers and establishes a connection to the database.
This class manages a list of database drivers. Matches connection requests from the java application with
proper database driver using communication sub protocol. The first driver that recognizes a certain sub
protocol under JDBC will be used to establish a database Connection.
E.g:
Mysql :
Connection con = [Link]("jdbc:mysql://localhost:3306/mydb", "root", "password");
2. JDBC Driver:
This interface handles the communications with the database server.
A JDBC driver can come from many sources: database software, such as Java DB, a JDBC driver vendor such
as DataDirect, Oracle, MySQL.
e.g.: The driver for Oracle is E.g.:
[Link]: It is Compatible with JDK 8
[Link]: Implements JDBC 4.3 spec and certified with JDK 11,
3. Connection
4. ResultSet
A ResultSet holds the rows and columns of data returned from a database query . It provides
cursor based navigation methods like next(), previous(), first(), last(), and many more.
It also provides a data retrieval functions as getString(), getInt(), getDouble(), and manymore.
[Link]("[Link]");
// Connect to database
1. Connection con = [Link](
"jdbc:mysql://localhost:3306/mydb", "root", "password");
// Process result
while([Link]()) {
[Link]([Link]("username"));
}
// Close connection
[Link]();
[Link]();
[Link]();
}
Types of JDBC Drivers
• There are four main types of JDBC drivers, categorized by their architecture and how they
connect to the database:
• Type 1: JDBC-ODBC Bridge Driver
Connectivity) calls. These ODBC calls are then passed to the ODBC driver, which communicates with
the actual database.
It represents a static SQL statement that is compiled and executed once without parameters.
Method Description
Executes a SQL SELECT query and returns a
executeQuery(String sql)
ResultSet.
Executes INSERT, UPDATE, or DELETE operations;
executeUpdate(String sql)
returns number of affected rows.
Executes any kind of SQL statement; returns true if
execute(String sql)
the result is a ResultSet, false otherwise.
close() Closes the statement and releases resources.
getResultSet() Returns the current ResultSet object (if available).
Returns the number of rows affected by the last
getUpdateCount()
operation.
Types of SQL Statements it Can Execute:
• Data Query Language (DQL): SELECT
• Data Manipulation Language (DML): INSERT, UPDATE, DELETE
• Data Definition Language (DDL): CREATE, DROP, ALTER
• Data Control Language (DCL): GRANT, REVOKE
Step 2: Create Statement: Create a statement object to excure simple SQL queries:
Step 3: Execute SQL Query: Execute the simple query using the API as shown below:
Step 4: Process Results: Once the query is executed, the results are stored in a temporary table. So, it to
fectch the result
while ([Link]()) { ... }
While it is straightforward and flexible, it should be used cautiously due to its lack of parameterization and
vulnerability to SQL injection.
For secure and efficient operations, especially involving user inputs, PreparedStatement is generally preferred.
Result set
ResultSet is an interface within the [Link] package that represents a table of data generated
by executing a database query.
It acts as a container for the results retrieved from a relational database and provides methods
to access and manipulate that data.
It acts like a cursor pointing to one row of data in the result set at a time.
Key characteristics of a ResultSet
• Data Representation: It holds the rows and columns that satisfy the conditions of an SQL
query, and acting as an in-memory representation of the query's output.
• Cursor-based Navigation: It maintains a cursor which acts a pointer the current row of
data. The methods to navigate are next(), first(), last() …
• Data Retrieval: It provides a set of get() methods to retrieve column values from the
current row such as getInt(), getDate(), getSring() etc.
• Updatability (Optional): Depending on the ResultSet type and concurrency mode, it can
also be used to update, insert, or delete rows in the underlying database
Types of ResultSet
• Readonly Resultset
• Updatable Resultset
• Forward only Resultset
• Scrollable Resultset
import [Link].*;
try {
// Establish connection (replace with your actual database details)
conn = [Link]("jdbc:mysql://localhost:3306/mydatabase", "user", "password");
// Create a Statement
stmt = [Link]();
• A Read-Only Result Set is a type of result set that does not allow updates to the data ie.,
allows only the retrieval of data.
• By default , JDBC Resultset is Readonly, But we can also specify explicitly as follows:
INSENSITIVE "Insensitive" to changes in the database (i.e., changes made to the data after the query runs are
not visible in the result set).
Statement stmt = [Link](
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY // or CONCUR_UPDATABLE
);
An Updatable ResultSet is a JDBC feature that allows you to modify, insert, and delete data
directly within a result set object, persisting these changes to the database using Java
methods like updateRow(), insertRow(), and deleteRow().
Key Aspects:
•In-Place Modification:
You can change the contents of existing rows, or insert new rows, or delete rows from
the database using the methods provided on the ResultSet object itself, rather than
writing separate SQL commands.
• Saving Changes:
After using update methods (updateString(), updateInt(), etc.) to modify a row, you must
call updateRow() to write those changes to the underlying database. For inserts, use insertRow(), and
for deletes, use deleteRow()
[Link](2); // Move to 2nd row
[Link]("name", “REVA");
[Link](); // Apply the update to the database
// ✅ Update row
[Link](1);
[Link]("name", "Updated Name");
[Link]();
// ✅ Delete row
[Link](2);
[Link]();
}
III. Forward Only Result Set
A forward-only result set is a non-scrollable data access object that allows movement through its data only in
the forward direction, from the first row to the last
A scrollable result set is a data object that allows a program to move a cursor both forward and
backward through the rows of a database query result
Scrollable result sets provide flexible navigation using methods like first(), last(), absolute(),
and previous().
TYPE_SCROLL_INSENSITIVE: This type of result set is scrollable, but it is not "sensitive" to changes
made to the underlying database by other transactions while the result set is open.
TYPE_SCROLL_SENSITIVE: This type is scrollable and sensitive to changes made to the database while
the result set is open
TYPE_SCROLL_SENSITIVE
Srn
Srn Name age
rs Srn Name age
11
11 Abc
soma 10
22
11 Abc
soma 10
22
12
12 rama
Pqr 33
11
12 Pqr
rama 11
33
Result set
TYPE_SCROLL: Cursor can move both forward and backward.
SENSITIVE It "sensitive" to changes in the database (i.e., changes made to the data after the query runs are
not visible in the result set).
Prepared statements
A PreparedStatement is a precompiled SQL statement in JDBC that allows you to execute the same
SQL query multiple times with different parameters
Syntax:
PreparedStatement pst = [Link]("SQL Query with ? placeholders");
E.g.
PreparedStatement pst = [Link]( "INSERT INTO students (id, name, marks) VALUES (?, ?, ?)");
ResultSet rs = [Link]();
while ([Link]()) {
[Link]([Link](“Name") + " " + [Link](“Salary"));
}
e.g: A program to insert a row
// 1. Establish connection
CREATE TABLE employees ( Connection con = [Link](url, user, password);
id INT AUTO_INCREMENT PRIMARY KEY,
// 2. Create SQL with placeholders
name VARCHAR(50), String sql = "INSERT INTO employees (name, age, salary) VALUES
age INT, (?, ?, ?)";
salary DOUBLE
// 3. Create PreparedStatement object
);
PreparedStatement pst = [Link](sql);
// 4. Set values
[Link](1, "Darshan"); // name
[Link](2, 25); // age
id Name Age Salary
[Link](3, 55000); // salary
11 Darshan 25 55000
// 5. Execute update
int rows = [Link]();
[Link](rows + " row(s) inserted successfully.");
// 6. Close connection
[Link]();
[Link]();
How prepared statements work
•Prepare phase:
• An application sends a statement template to the database management system (DBMS).
• The template contains the static SQL code with placeholders, such as question marks (?), for
values that will be provided later.
• The DBMS parses, compiles, and optimizes this template, and generates a execution plan.
•Execute phase:
• The application binds the actual parameter values to the placeholders and sends them to the
database.
• The DBMS executes the compiled query with the new data as per the execution plan.
• This can be repeated with different data without the need to re-compile the query.
Advantages of prepared statements:
• Precompiled for Performance: The SQL query is compiled by the database only once, even
if executed multiple times with different values.
• Prevents SQL Injection: Uses placeholders (?) and automatically escapes special characters.
protects against malicious inputs.
• Easier to Read & Maintain: SQL query is written only once with placeholders.
• Batch Execution Support: Allows you to add multiple sets of values (addBatch()) and
execute them together (executeBatch()), improving performance.
SQL Injection
• SQL injection (SQLi) is a web security vulnerability where an attacker can interfere with a
website's database queries.
• By injecting malicious SQL code into input fields, attackers can bypass security, access data, or
even destroy it.
• SQL injection occurs when applications concatenate user input directly into SQL queries
"select * from user where username = ' " + username + " ' ";
Now if username variable is filled by third party, then there are chances that user data contains SQL like
Final Query :
"select * from user where username = ' jayesh'; delete from user where id='1 ' ";
Upon execution it will delete the record from user table which was never the purpose of original
query and this is called SQL Injection attack.
Step-by-step how prepared statements prevents SQL Injection:
1. Prepare (parse + compile):
The SQL text with placeholders (?) to the DB are parsed it and builds an execution
plan.
[Link] values :
The values send separately are replaced with ‘?’ and the DB engine treats them as
data only, not as SQL tokens.
[Link] :
The DB runs the compiled plan using the bound data.
Since the SQL structure (Execution plan) was decided before the data arrived,
injected text can’t alter the SQL syntax.
Batch Updation
Batch updates in JDBC refer to the process of grouping multiple SQL INSERT, UPDATE,
or DELETE statements together and submitting them to the database for execution as a single
unit.
• This approach significantly improves performance compared to executing each statement individually.
• When used with PreparedStatement, we prepare the SQL once, then repeatedly set different parameter values
and add them to a batch, and finally run them all at once with executeBatch()
Two ways of Batch creation
1. Using statement object
2. Using prepared statement object.
try{
Connection con = [Link](url, user, password);
Statement stmt = [Link]()
// Execute batch
int[] results = [Link]();
[Link]();
[Link]("Batch executed successfully!");
for (int count : results) {
[Link]("Rows affected: " + count);
}
Using prepared statement object
A stored procedure is a precompiled block of SQL statements stored in the database that can be
executed with a single call.
It is nothing but the group of SQL statements that accepts some input in the form of parameters
and performs some task and may or may not returns a value.
1. IN: This is the Default Parameter for the procedure. It always receives the values from calling program.
2. OUT: This parameter always sends the values to the calling program.
3. IN OUT: This parameter performs both the operations. It receives value from as well as sends the
values to the calling program.
CREATE PROCEDURE getEmployeeSalary( IN emp_id INT, OUT emp_salary DECIMAL(10,2))
BEGIN
SELECT salary INTO emp_salary FROM employees WHERE id = emp_id;
END;
Explanation:
CREATE PROCEDURE getEmployeeSalary(...) : Declares a stored procedure named getEmployeeSalary in the current
database.
•IN emp_id INT: IN parameter: a value passed into the procedure. Here emp_id is an integer input (the employee id you want to
look up).
•OUT emp_salary DECIMAL(10,2): OUT parameter: used to return a value from the procedure back to the caller.
DECIMAL(10,2) means a fixed-point numeric with up to 10 total digits.
•BEGIN ... END: Procedure body where you put SQL statements. Note: in MySQL you usually need to change the client delimiter
before creating a procedure (see below).
This runs a query and stores the salary value into the local/OUT variable emp_salary.
CREATE PROCEDURE getEmployeeSalary( IN emp_id INT, OUT emp_salary DECIMAL(10,2))
BEGIN
SELECT salary INTO emp_salary FROM employees WHERE id = emp_id;
END;
@salary
Output: _______________
55000.00
Callable statements
A CallableStatement is an interface in the JDBC API (in [Link] package) that is used to call stored procedures
and functions in a relational database
2. Create the CallableStatement object : Use the prepareCall() method of the Connection object, passing the stored
routine call in JDBC escape syntax
3. Register OUT parameters: Before execution, all OUT and INOUT parameters are to be registered with the appropriate JDBC
data type.
[Link]("[Link]");
Connection con = [Link]("jdbc:mysql://localhost:3306/mydb", "root", "password");
if (salary != null) {
[Link]("Employee Salary = " + salary);
} else {
[Link]("No salary found for this employee ID.");
}
Multiple OUT parameters Connection con = [Link](
"jdbc:mysql://localhost:3306/mydb", "root", "password");
CREATE PROCEDURE
CallableStatement cstmt = [Link]("{call getEmployeeDetails(?, ?, ?)}");
getEmployeeDetails( IN emp_id INT,
OUT emp_salary DECIMAL(10,2), [Link](1, 101); // IN param
OUT emp_dept VARCHAR(50)
// OUT params
) [Link](2, [Link]); // salary
BEGIN [Link](3, [Link]); // department
SELECT salary, department
INTO emp_salary, emp_dept [Link](); // Execute
FROM employees
double salary = [Link](2); // Retrieve multiple OUT values
WHERE id = emp_id;
String dept = [Link](3);
END;
[Link]("Salary: " + salary);
[Link]("Department: " + dept);
Thank You