0% found this document useful (0 votes)
5 views57 pages

Understanding JDBC in Java Programming

The document provides an overview of JDBC (Java Database Connectivity), a Java API that facilitates interaction between Java applications and databases. It details the architecture of JDBC, including its core and extension APIs, key components like DriverManager, JDBC drivers, and the types of SQL statements that can be executed. Additionally, it explains the ResultSet interface and its characteristics, types, and methods for data manipulation within a database context.

Uploaded by

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

Understanding JDBC in Java Programming

The document provides an overview of JDBC (Java Database Connectivity), a Java API that facilitates interaction between Java applications and databases. It details the architecture of JDBC, including its core and extension APIs, key components like DriverManager, JDBC drivers, and the types of SQL statements that can be executed. Additionally, it explains the ResultSet interface and its characteristics, types, and methods for data manipulation within a database context.

Uploaded by

jw9410762
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

School of Computer Science and

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 core API [Link]: JDBC Architecture


JDBC Overview
• JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational
Database.
• JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of
UNIX.
• JDBC stands for Java Database Connectivity, which is a standard Java API for database independent
connectivity between the Java programming language and a wide range of databases.
• The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated
with database usage.
▪ Making a connection to a database.
▪ Creating SQL or MySQL statements.
▪ Executing SQL or MySQL queries in the database.
▪ Viewing & Modifying the resulting records.
The JDBC API is defined by two packages in Java:
• The core API [Link]: It provides the API for accessing and processing the data stored in a database
(usually a relational database) using Java. This package provides the foundation and most commonly used
objects such as Connection, ResultSet, Statement, and PreparedStatement. The DriverManager class
is the main component here that loads drivers and retrieves a connection.

• 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.

The Key Concepts of JDBC:

• 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.

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

Data source location

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

•Represents a session with the database.


•Used to create statements and manage transactions.
•This interface with all methods for contacting a database. The connection object represents
communication context, i.e., all communication with database is through connection object only.
3. Statement / PreparedStatement / CallableStatement
It is used to execute SQL queries:
• Statement : The general SQL queries such as select, insert, update, delete, etc.
•PreparedStatement : These are precompiled SQL queries along with parameters
•CallableStatement : These statements for stored procedures.

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");

// Create and execute query


2. Statement stmt = [Link]();

3. ResultSet rs = [Link]("SELECT * FROM users");

// 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

• Type 2: Native-API Driver

• Type 3: Network Protocol Driver

• Type 4: Thin Driver (Pure Java Driver)


Type 1: JDBC-ODBC Bridge Driver :
• Uses ODBC driver to connect to the database. Translates JDBC calls to ODBC calls.
• The JDBC-ODBC Bridge Driver takes these JDBC calls and converts them into ODBC (Open Database

Connectivity) calls. These ODBC calls are then passed to the ODBC driver, which communicates with
the actual database.

Java App (JDBC API)



JDBC-ODBC Bridge Driver (Type 1)

ODBC Driver

Database
Type 2: Native-API Driver
The Type 2 driver uses native database APIs (Application Programming Interfaces) to
communicate directly with the database.
It acts as a wrapper around the vendor’s native database client libraries.
The JDBC calls from your Java program are translated into calls to native libraries specific to the database.

Java App (JDBC API)



Type 2 JDBC Driver (Java code)

Native DB Client API (C/C++ libraries provided by DB vendor)

Database

The driver is partly Java, partly native code (platform-dependent).


Type 3: Network Protocol Driver
Sends JDBC calls to a middleware server, which translates to DB-specific calls.
The Type 3 driver acts as a middleware server or application server proxy between the Java application
and the database.
It translates JDBC calls into a database-independent network protocol, sends them to the middleware
server.
The middleware then converts these calls into the native database calls.
Java App (JDBC API)

Type 3 JDBC Driver (Java code)

Middleware Server (translates protocol)

Database
The client-side driver is written entirely in Java.
The middleware server handles all database-specific communication.
The middleware can support multiple database types, offering database independence.
Type 4: Thin Driver (Pure Java Driver)
Directly converts JDBC calls to database protocol. Fully written in Java
The Type 4 driver is a 100% Java implementation.
It converts JDBC calls directly into the database’s network protocol.
No native code or middleware is involved — communication happens straight over
TCP/IP between the Java app and the database server.
Because it’s pure Java, it is platform-independent.

Java App (JDBC API)



Type 4 JDBC Driver (Pure Java)

Database (over network protocol)
Statement
The Statement interface is part of the [Link] package and is used to send SQL commands to the
database from a Java application.

It is used primarily for:


•Static SQL queries (hardcoded strings with no placeholders).
•General-purpose SQL execution.

It represents a static SQL statement that is compiled and executed once without parameters.

It returns results in the form of:


• ResultSet (for SELECT queries)
• Integer (for UPDATE/INSERT/DELETE)
• Boolean (for general SQL execution)
Syntax:
Statement stmt = [Link]();
The Important methods of statements objects are:

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

The Life Cycle of Statement Execution:


Step 1: Establish Connection: Establish a connection using driver manager object as shown below:
Connection conn = [Link](...);

Step 2: Create Statement: Create a statement object to excure simple SQL queries:

Statement stmt = [Link]();

Step 3: Execute SQL Query: Execute the simple query using the API as shown below:

ResultSet rs = [Link]("SELECT * FROM table_name");

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]()) { ... }

Step 5: Close all the connection using close() API.


The Statement object is a foundational component of JDBC, allowing Java applications to interact with relational
databases using SQL commands.

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.

ResultSet rs = [Link]("SELECT * FROM table_name");

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].*;

public class ResultSetExample {


public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try {
// Establish connection (replace with your actual database details)
conn = [Link]("jdbc:mysql://localhost:3306/mydatabase", "user", "password");

// Create a Statement
stmt = [Link]();

// Execute a query and get the ResultSet


rs = [Link]("SELECT id, name, age FROM employees");

// Iterate through the ResultSet


while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
int age = [Link]("age");
[Link]("ID: " + id + ", Name: " + name + ", Age: " + age);
}
I. Read-only Resultset

• 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:

Statement stmt = [Link](


ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY
);

ResultSet rs = [Link]("SELECT * FROM employees");


TYPE_SCROLL_INSENSITIVE

It is a ResultSet type that allows the programmer to perform:


•Scroll the cursor in any direction (forward, backward, jump to any row) using next(),
first(), last() etc.
•Does not reflect changes made in the database after the ResultSet was created.

Srn Name age


rs Srn Name age
11 Abc 10
11 Abc
soma 10
22
12 Pqr 11
12 Pqr
rama 11
33
Result set
TYPE_SCROLL: Cursor can move both forward and backward.

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
);

ResultSet rs = [Link]("SELECT * FROM employees");


// Navigate using cursor movement
[Link](); // Moves to first row
[Link](); // Moves to last row
[Link](3); // Moves to 3rd row
[Link](); // Moves one row back
[Link](-2); // Moves back 2 rows
ResultSet.CONCUR_READ_ONLY

CONCUR_READ_ONLY ensures that the result set can be :


• only fetch and read data.
•It cannot modify the result set or underlying database through the ResultSet object.
•It's the default concurrency mode in JDBC.
•Ensures better performance and data integrity for read-heavy operations like reporting or
data analysis.
II. Upatable ResultSet:

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

Srn Name age


rs Srn Name age
11 Abc 10
11 Abc 10
12 Pqr
REVA 11
12 Pqr
REVA 11
Result set
try {
Connection conn = [Link](url, user, password);
Statement stmt = [Link](
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE

ResultSet rs = [Link]("SELECT id, name FROM employees");

// ✅ Update row
[Link](1);
[Link]("name", "Updated Name");
[Link]();

// ✅ Insert new row


[Link]();
[Link]("id", 106);
[Link]("name", "New Employee");
[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

You can only use [Link]() to move to the next row


No backward navigation (previous(), first(), last(), absolute() etc. are NOT allowed).
Cursor moves in a linear way: 1 ->2 -> 3 ->️

Statement stmt = [Link](


ResultSet.TYPE_FORWARD_ONLY, // Cursor can only move forward
ResultSet.CONCUR_READ_ONLY // Read-only (default)
);

ResultSet rs = [Link]("SELECT * FROM employees");


while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
[Link]("ID: " + id + ", Name: " +
name);
}

while ([Link]()) { These will throw a SQLException:


int id = [Link]("id"); •[Link]()
String name = [Link]("name"); •[Link]()
•[Link]()
[Link]("ID: " + id + ", Name: " + name); •[Link](3)
[Link](5) SQL exception •[Link](-1)
}
IV. Scrollable Resultset

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().

Types of scrollable result sets

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

It is a ResultSet type that allows the programmer to perform:


•Scroll the cursor in any direction (forward, backward, jump to any row) using next(),
first(), last() etc.
•It reflects changes during transaction after the ResultSet was created.

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

• Uses placeholders (?) to safely pass values at runtime


• Provides better performance and prevents SQL injection.

Syntax:
PreparedStatement pst = [Link]("SQL Query with ? placeholders");

E.g.
PreparedStatement pst = [Link]( "INSERT INTO students (id, name, marks) VALUES (?, ?, ?)");

[Link](1, 101); //First ?  replaced to 101


[Link](2, "Asha"); //Second ?  replaced to Asha
[Link](3, 95);
String sql = "SELECT Name, Salary FROM Employee WHERE empid = ?";

PreparedStatement pst = [Link](sql);

[Link](1, 101); // set condition

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

The process of a prepared statement happens in two distinct phases:

"select * from user where username = ?;

•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

username = “jayesh;delete from user where id='1"

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.

Steps in batch creation using Statement object


• Step 1: Get a connection to the database using getConnection().

• Step 2: Create a statement object using connection object.

• Step 3: Use addBatch(SQL) to add multiple SQL queries.

• Step 4: Call executeBatch() function to execute all sql queries.


Using statement object

String url = "jdbc:mysql://localhost:3306/testdb";


String user = "root";
String password = "password";

try{
Connection con = [Link](url, user, password);
Statement stmt = [Link]()

// Add multiple queries in batch


[Link]("INSERT INTO employees (name, age, salary) VALUES ('Ravi', 30, 4000)");
[Link]("INSERT INTO employees (name, age, salary) VALUES ('Sneha', 26, 5000)");
[Link]("DELETE FROM employees WHERE name = 'Bob'");

// Execute batch
int[] results = [Link]();
[Link]();
[Link]("Batch executed successfully!");
for (int count : results) {
[Link]("Rows affected: " + count);
}
Using prepared statement object

The Steps are :


• Step 1: Get a connection to the database using getConnection().

• Step 2: Create a Prepared statement object using connection object.

• Step 3: Set parameter values for each record

• Step 3: Use addBatch(SQL) to add multiple SQL queries.

• Step 4: Call executeBatch() function to execute all sql queries.


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

String sql = "INSERT INTO employees (name, age, salary) VALUES(?,


?, ?)";
PreparedStatement ps = [Link](sql); // Execute batch
int[] results = [Link]();
// 1st record [Link]();
[Link](1, "Amit");
[Link](2, 29); for (int count : results) {
[Link](3, 48000); [Link]("Rows affected: " +
[Link](); count);
}
// 2nd record
[Link](1, "Priya");
[Link](2, 34);
[Link](3, 60000);
[Link]();
Stored procedures

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.

Syntax : Creating a Procedure


CREATE PROCEDURE Procedure_name( [IN|OUT] <parameter> <datatype>)
BEGIN
<Local declaration>;
<Procedure-body>
END;
The most important part is parameters. Parameters are used to pass values to the Procedure.
There are 3 different types of parameters, they are as follows:

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).

SELECT salary INTO emp_salary FROM employees WHERE id = emp_id;

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;

CALL getEmployeeSalary(101, @salary);


SELECT @salary;

@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

CallableStatement cstmt = [Link] (“ {call procedure_name(?, ?, ?) }“ );

The steps to create a CallableStatement


1. Establish a database connection:
Connection con = [Link](url, user, password);

2. Create the CallableStatement object : Use the prepareCall() method of the Connection object, passing the stored
routine call in JDBC escape syntax

CallableStatement cstmt = [Link]("{call procedure_name(?, ?)}");

3. Register OUT parameters: Before execution, all OUT and INOUT parameters are to be registered with the appropriate JDBC
data type.

// Register the second parameter as an OUT parameter of type VARCHAR


[Link](2, [Link]);
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;

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

CallableStatement cstmt = [Link](“ {call getEmployeeSalary(?, ?)}“ ); // 3. Create CallableStatement


[Link](1, 101); // 4. Set IN parameter (emp_id)

[Link](2, [Link]); // 5. Register OUT parameter (emp_salary)

[Link](); // 6. Execute the procedure

BigDecimal salary = [Link](2); // 7. Retrieve OUT parameter

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

You might also like