JDBC CallableStatement Interface
Java developers use the CallableStatement interface which extends PreparedStatement to invoke stored procedures in relational databases. Stored procedures consist of SQL code that remains in the database for multiple calls with varying parameters.
Key Features
- Used for calling stored procedures
- Can accept IN, OUT, and INOUT parameters
- Extends PreparedStatement
- Supports batch execution and transactions
Syntax
import java.sql.CallableStatement;
CallableStatement cs = connection.prepareCall("{call getEmployee(?)}");
Methods
| Method | Description |
|---|---|
| setInt(index, value) | Sets IN parameter |
| registerOutParameter(index, type) | Registers OUT parameter |
| getInt(index) | Gets OUT parameter after execution |
| execute() | Executes the stored procedure |
| close() | Closes the CallableStatement |
Example
import java.sql.*;
public class CallableStatementExample {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "password");
// Prepare call
CallableStatement cs = con.prepareCall("{call getEmployee(?)}");
// Set IN parameter
cs.setInt(1, 101);
// Execute
ResultSet rs = cs.executeQuery();
// Process results
while (rs.next()) {
System.out.println(rs.getInt("id") + " - " + rs.getString("name"));
}
cs.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Statement vs PreparedStatement vs CallableStatement
| Feature | Statement | PreparedStatement | CallableStatement |
|---|---|---|---|
| SQL Injection Safe | ❌ | ✅ | ✅ |
| Reusability | ❌ | ✅ | ✅ |
| Used For | Static SQL | Parameterized SQL | Calling stored procedures |
| Supports Parameters | No | Yes (?) | Yes (IN, OUT, INOUT) |
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com