Introduction
When developing Java applications that interact with relational databases, you may need to execute stored procedures instead of writing SQL queries directly in your Java code. Stored procedures are precompiled SQL programs stored inside the database that perform one or more database operations.
JDBC provides the CallableStatement interface to execute stored procedures from a Java application. It extends the PreparedStatement interface and supports input (IN), output (OUT), and input-output (INOUT) parameters, making it suitable for complex database operations.
Using CallableStatement offers several benefits, including improved performance, better code organization, enhanced security, and reduced network traffic. It is commonly used in enterprise applications where business logic is partially implemented inside the database.
What is CallableStatement?
CallableStatement is an interface in the java.sql package that is used to execute stored procedures in a relational database.
It extends the PreparedStatement interface, so it inherits all of its features while adding support for stored procedure execution and output parameters.
A CallableStatement can:
- Execute stored procedures.
- Pass input values.
- Receive output values.
- Execute procedures that return result sets.
- Execute procedures that perform multiple database operations.
Why Use CallableStatement?
Using CallableStatement provides several advantages.
- Executes stored procedures directly.
- Supports IN, OUT, and INOUT parameters.
- Improves performance through precompiled stored procedures.
- Reduces network traffic by executing logic on the database server.
- Keeps business logic centralized inside the database.
- Enhances security by avoiding direct SQL exposure.
Syntax
The general syntax is:
Connection con = DriverManager.getConnection(url, username, password);
CallableStatement cs =
con.prepareCall("{call procedure_name(?)}");
If the procedure has multiple parameters:
CallableStatement cs =
con.prepareCall("{call procedure_name(?,?,?)}");
Each ? represents a parameter.
How CallableStatement Works
The execution flow is as follows:
- Create a stored procedure in the database.
- Establish a JDBC connection.
- Create a CallableStatement object.
- Set input parameter values.
- Register output parameters if required.
- Execute the stored procedure.
- Read output values or result sets.
- Close all JDBC resources.
Creating a Sample Database
Create the database.
CREATE DATABASE company;
Use the database.
USE company;
Create the employee table.
CREATE TABLE employee(
id INT PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(50),
salary DOUBLE
);
Insert sample records.
INSERT INTO employee VALUES
(101,'Rahul','IT',55000),
(102,'Amit','HR',45000),
(103,'Neha','Finance',65000);
Example 1: Stored Procedure Without Parameters
Create the stored procedure.
DELIMITER $$
CREATE PROCEDURE GetEmployees()
BEGIN
SELECT * FROM employee;
END$$
DELIMITER ;
Java program:
import java.sql.*;
public class CallableStatementExample {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/company",
"root",
"password");
CallableStatement cs =
con.prepareCall("{call GetEmployees()}");
ResultSet rs = cs.executeQuery();
while(rs.next()) {
System.out.println(
rs.getInt("id") + " " +
rs.getString("name") + " " +
rs.getDouble("salary"));
}
rs.close();
cs.close();
con.close();
} catch(Exception e)
e.printStackTrace();
}
}
}
Output
102 Amit 45000.0
103 Neha 65000.0
Example 2: Stored Procedure with IN Parameter
Create the stored procedure.
DELIMITER $$
CREATE PROCEDURE GetEmployee(IN empId INT)
BEGIN
SELECT * FROM employee
WHERE id = empId;
END$
DELIMITER ;
Java program:
CallableStatement cs =
con.prepareCall("{call GetEmployee(?)}");
cs.setInt(1,101);
ResultSet rs = cs.executeQuery();
The value 101 is passed as the input parameter.
Example 3: Stored Procedure with OUT Parameter
Create the procedure.
DLIMITER $$
CREATE PROCEDURE GetSalary(
IN empId INT,
OUT empSalary DOUBLE
)
BEGIN
SELECT salary
INTO empSalary
FROM employee
WHERE id = empId;
END$$
DELIMITER ;
Java program:
CallableStatement cs =
con.prepareCall("{call GetSalary(?,?)}");
cs.setInt(1,101);
cs.registerOutParameter(2, Types.DOUBLE);
cs.execute();
double salary = cs.getDouble(2);
System.out.println(salary);
Output
Example 4: Stored Procedure with INOUT Parameter
Suppose a stored procedure receives a salary and returns the updated salary after adding a bonus.
Java code:
CallableStatement cs =
con.prepareCall("{call UpdateBonus(?)}");
cs.setDouble(1,50000);
cs.registerOutParameter(1,Types.DOUBLE);
cs.execute();
System.out.println(cs.getDouble(1));
INOUT parameters are commonly used when the same parameter is used as both input and output.
Common Methods of CallableStatement
| Method | Description |
|---|---|
| setInt() | Sets an integer parameter |
| setString() | Sets a string parameter |
| setDouble() | Sets a double parameter |
| registerOutParameter() | Registers an OUT parameter |
| execute() | Executes the stored procedure |
| executeQuery() | Executes procedures returning a result set |
| executeUpdate() | Executes procedures that modify data |
| getInt() | Retrieves an integer OUT parameter |
| getString() | Retrieves a string OUT parameter |
| getDouble() | Retrieves a double OUT parameter |
| close() | Closes the CallableStatement |
IN, OUT, and INOUT Parameters
| Parameter Type | Description |
|---|---|
| IN | Receives values from Java |
| OUT | Returns values to Java |
| INOUT | Acts as both input and output |
Example:
Java
│
▼
Stored Procedure
│
├── IN Parameter
├── OUT Parameter
└── INOUT Parameter
CallableStatement Workflow
Java Application
│
▼
Database Connection
│
▼
CallableStatement
│
▼
Stored Procedure
│
▼
Database
│
▼
Result / Output Parameters
│
▼
Java Application
CallableStatement vs PreparedStatement
| Feature | PreparedStatement | CallableStatement |
|---|---|---|
| Executes SQL | Yes | Yes |
| Executes Stored Procedures | No | Yes |
| Supports OUT Parameters | No | Yes |
| Supports INOUT Parameters | No | Yes |
| Performance/td> | High | igh for stored procedures |
| Used For | SQL Queries | Stored Procedures |
Advantages of CallableStatement
Using CallableStatement provides several benefits.
- Executes stored procedures efficiently.
- Improves application performance.
- Reduces SQL code in Java programs.
- Supports complex business logic.
- Supports IN, OUT, and INOUT parameters.
- Increases code reusability.
- Enhances security by limiting direct SQL access.
- Suitable for enterprise applications.
Real-life Example
Consider a Banking Application.
When transferring money between two accounts, several operations must occur:
- Verify the sender’s balance.
- Deduct the transfer amount.
- Credit the receiver’s account.
- Record the transaction.
- Generate a transaction ID.
Instead of sending multiple SQL queries from Java, a stored procedure performs all these operations in one place. The Java application calls this procedure using CallableStatement, reducing network traffic and ensuring data consistency.
Other common use cases include:
- Payroll processing
- Order processing
- Hospital billing systems
- Inventory management
- Student result processing
- Insurance claim management
Best Practices
Follow these best practices when using CallableStatement:
- Use meaningful stored procedure names.
- Validate input values before calling procedures.
- Register all OUT parameters before execution.
- Use try-with-resources to close JDBC resources automatically.
- Handle SQLException properly.
- Keep stored procedures focused on a single task.
- Document procedure parameters clearly.
- Test procedures independently before integrating them with Java.
Common Mistakes
Avoid these common mistakes:
- Forgetting to register OUT parameters.
- Using incorrect parameter indexes.
- Setting parameters in the wrong order.
- Using incompatible data types.
- Not closing CallableStatement objects.
- Ignoring SQL exceptions.
- Calling a procedure that does not exist.
- Forgetting to commit transactions when auto-commit is disabled.
Conclusion
CallableStatement is a powerful JDBC interface for executing stored procedures from Java applications. It extends the capabilities of PreparedStatement by supporting stored procedures with IN, OUT, and INOUT parameters. This makes it ideal for implementing complex database operations while improving performance and maintaining cleaner application code.
By understanding how to create, execute, and manage stored procedures with CallableStatement, you can build secure, scalable, and enterprise-ready Java applications. It is an essential topic for both real-world development and Java interviews, especially when working with large-scale database systems.