How do I register out parameter in CallableStatement?

This example show you how to register out parameter for executing a stored procedure using the CallableStatement.registerOutParameter() method call. We must register the out parameters before the query execution. The registerOutParameter() method takes two parameters, the index of the parameter and the sql data type of the out parameter.

package org.kodejava.example.jdbc;

import java.sql.*;

public class RegisterOutParameter {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "";

    public static void main(String[] args) {
        try (Connection connection =
                 DriverManager.getConnection(URL, USERNAME, PASSWORD)) {

            // Creates a CallableStatement for executing the stored
            // procedure
            String query = "call GetDetailByName(?, ?, ?)";
            CallableStatement cb = connection.prepareCall(query);

            // Sets the input parameter
            cb.setString(1, "Ruby on Rails");

            // Registers the out parameters
            cb.registerOutParameter(2, Types.VARCHAR);
            cb.registerOutParameter(3, Types.DECIMAL);

            // Executes the query

            // Gets the query result output
            System.out.println("Name  : " + cb.getString(1));
            System.out.println("Code  : " + cb.getString(2));
            System.out.println("Price : " + cb.getBigDecimal(3));
        } catch (SQLException e) {

Here is the MySQL stored procedure that we call in the code above.

CREATE PROCEDURE `GetDetailByName`(INOUT  product_name  VARCHAR(50),
                                   OUT product_code  VARCHAR(10),
                                   OUT product_price DECIMAL(10, 2))
    SELECT code INTO product_code FROM products WHERE name = product_name;

    SELECT price INTO product_price FROM products WHERE name = product_name;

Maven dependencies

<!-- -->

Maven Central

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.