Java Notes
Complete guide to CallableStatement — calling stored procedures and functions, IN/OUT/INOUT parameters, and handling multiple result sets from MySQL procedures.
What is CallableStatement?
CallableStatement is used to execute stored procedures and stored functions in the database. It extends PreparedStatement and adds support for OUT and INOUT parameters.
Calling Procedures with IN Parameters
import java.sql.*;
public class CallableStatementDemo {
private static final String URL = "jdbc:mysql://localhost:3306/java_course?useSSL=false&serverTimezone=UTC";
// Simple procedure call with IN parameter
public static void getEmployee(int empId) throws SQLException {
String sql = "{CALL get_employee(?)}"; // Standard JDBC escape syntax
try (Connection conn = DriverManager.getConnection(URL, "root", "password");
CallableStatement cstmt = conn.prepareCall(sql)) {
cstmt.setInt(1, empId); // Set IN parameter
try (ResultSet rs = cstmt.executeQuery()) {
if (rs.next()) {
System.out.printf("Employee: %s %s | Dept: %s | Salary: $%.2f%n",
rs.getString("first_name"),
rs.getString("last_name"),
rs.getString("department"),
rs.getDouble("salary"));
} else {
System.out.println("Employee not found: " + empId);
}
}
}
}
}OUT Parameters
public static int getEmployeeCount(String department) throws SQLException {
String sql = "{CALL get_employee_count(?, ?)}";
try (Connection conn = DriverManager.getConnection(URL, "root", "password");
CallableStatement cstmt = conn.prepareCall(sql)) {
// Set IN parameter
cstmt.setString(1, department);
// Register OUT parameter (must specify SQL type)
cstmt.registerOutParameter(2, Types.INTEGER);
// Execute
cstmt.execute();
// Get OUT parameter value
int count = cstmt.getInt(2);
System.out.println(department + " has " + count + " employees");
return count;
}
}INOUT Parameters
public static double adjustSalary(int empId, double raiseAmount) throws SQLException {
String sql = "{CALL adjust_salary(?, ?)}";
try (Connection conn = DriverManager.getConnection(URL, "root", "password");
CallableStatement cstmt = conn.prepareCall(sql)) {
// First param: IN (employee ID)
cstmt.setInt(1, empId);
// Second param: INOUT (pass raise amount, get new salary back)
cstmt.setDouble(2, raiseAmount);
cstmt.registerOutParameter(2, Types.DECIMAL);
cstmt.execute();
double newSalary = cstmt.getDouble(2);
System.out.printf("Employee %d new salary: $%.2f%n", empId, newSalary);
return newSalary;
}
}Calling Stored Functions
public static double calculateBonus(int empId) throws SQLException {
// Function call syntax: {? = call function_name(?)}
String sql = "{? = CALL calculate_bonus(?)}";
try (Connection conn = DriverManager.getConnection(URL, "root", "password");
CallableStatement cstmt = conn.prepareCall(sql)) {
// Register return value (first ?)
cstmt.registerOutParameter(1, Types.DECIMAL);
// Set input parameter (second ?)
cstmt.setInt(2, empId);
cstmt.execute();
double bonus = cstmt.getDouble(1);
System.out.printf("Bonus for employee %d: $%.2f%n", empId, bonus);
return bonus;
}
}Multiple Result Sets
\n=== " + department + " Employees === \n=== Department Statistics ===
Named Parameters (using index alternative)
// MySQL doesn't support named parameters natively
// But you can use named indices for clarity:
public static void namedParameterPattern(String dept, double minSalary) throws SQLException {
String sql = "{CALL search_employees(?, ?, ?)}";
try (Connection conn = DriverManager.getConnection(URL, "root", "password");
CallableStatement cstmt = conn.prepareCall(sql)) {
final int PARAM_DEPT = 1;
final int PARAM_MIN_SALARY = 2;
final int PARAM_RESULT_COUNT = 3;
cstmt.setString(PARAM_DEPT, dept);
cstmt.setDouble(PARAM_MIN_SALARY, minSalary);
cstmt.registerOutParameter(PARAM_RESULT_COUNT, Types.INTEGER);
ResultSet rs = cstmt.executeQuery();
while (rs.next()) {
// Process results
}
int totalFound = cstmt.getInt(PARAM_RESULT_COUNT);
System.out.println("Found: " + totalFound);
}
}Error Handling with Stored Procedures
Interview Questions
Q1: What is CallableStatement and when do you use it?
Answer: CallableStatement is used to call stored procedures and functions in the database. Use it when business logic is implemented in database procedures, for complex operations that benefit from server-side execution, or when calling legacy database procedures.
Q2: What is the syntax difference between calling a procedure and a function?
Answer: Procedure: {CALL procedure_name(?, ?)}. Function: {? = CALL function_name(?)} — the first ? is the return value which must be registered as an OUT parameter.
Q3: Explain IN, OUT, and INOUT parameters.
Answer: IN parameters pass values to the procedure (like method arguments). OUT parameters receive values from the procedure (like return values). INOUT parameters both send a value in and receive a modified value back. OUT/INOUT must be registered with registerOutParameter().
Q4: How do you handle multiple result sets from a stored procedure?
Answer: Call execute(), then loop using getMoreResults(). Check if current result is a ResultSet (getResultSet()) or an update count (getUpdateCount()). Loop until both return null/-1.
Q5: Why use stored procedures vs inline SQL?
Answer: Stored procedures offer: reduced network traffic (one call vs many), precompiled execution plans, centralized business logic, security (GRANT EXECUTE without table access), and atomic complex operations. Downsides: harder to version control, database-specific syntax.
Summary
In this chapter, we learned about CallableStatement in JDBC in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for CallableStatement in JDBC.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, jdbc, callable, statement
Related Java Master Course Topics