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)



Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.