How do I execute stored procedure?

Stored-procedure are user-generated functions or procedures that, once created in the database, it can be called by the client applications, such as Java application. In this example we’ll demonstrate how to use the JDBC java.sql.CallableStatement to call a stored procedure. The store procedure in this example is just for selecting records from the products table.

package org.kodejava.jdbc;

import java.sql.*;

public class CallableStatementDemo {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

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

            // Create a CallableStatement to execute the GetAllProducts() 
            // procedure.
            CallableStatement stmt =
                    connection.prepareCall("{CALL Get_All_Products()}");

            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getLong("id") + "\t"
                        + rs.getString("code") + "\t"
                        + rs.getString("name") + "\t"
                        + rs.getDouble("price"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Below is the stored procedure definition that was executed in the code above.

DELIMITER ;;
CREATE PROCEDURE `Get_All_Products`()
BEGIN
    SELECT * FROM product;
END;;
DELIMITER ;

When running the code snippet, the result will be something like this:

1   P0000001    UML Distilled 3rd Edition   25.0
3   P0000003    PHP Programming 20.0
4   P0000004    Longman Active Study Dictionary 40.0
5   P0000005    Ruby on Rails   24.0
6   P0000006    Championship Manager    0.0
7   P0000007    Transport Tycoon Deluxe 0.0
8   P0000008    Roller Coaster Tycoon 3 0.0
9   P0000009    Pro Evolution Soccer    0.0
10  P0000010    Data Structures, Algorithms 50.99

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.1.0</version>
</dependency>

Maven Central

Wayan

Leave a Reply

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