Friday, 15 May 2015

JDBC - CallableStatement (Mysql)

🚀 Master Java database programming, JDBC, and MySQL stored procedures!

🔔 Subscribe to Ram N Java on YouTube

Calling MySQL Stored Procedures with JDBC CallableStatement

In MySQL, stored procedures are precompiled collections of SQL queries stored directly inside the database catalog. Using stored procedures improves performance, centralizes business logic, and helps secure database operations.

In Java, the CallableStatement interface provides a standard mechanism to invoke stored procedures and retrieve the resulting ResultSet directly into your application.

The MySQL Stored Procedure (get_all_cities)

Below is the stored procedure created in the MySQL world database. When called, it executes a query returning all records from the city table:

DELIMITER $$

CREATE PROCEDURE `get_all_cities`()
BEGIN
    SELECT * FROM city;
END$$

DELIMITER ;

Complete Java Source Code Example

The following Java program loads the MySQL JDBC driver, establishes a connection, executes the stored procedure using prepareCall(), and prints the result set:

package com.ram.jdbc;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCCallableStatementDemo {

    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/world";
    static final String USER = "root";
    static final String PASS = "root";

    public static void main(String[] args) {
        JDBCCallableStatementDemo demo = new JDBCCallableStatementDemo();
        demo.getAllCitiesInfo();
    }

    public void getAllCitiesInfo() {
        Connection conn = null;
        CallableStatement cstmt = null;
        ResultSet rs = null;

        try {
            // Step 1: Register MySQL JDBC Driver
            Class.forName(JDBC_DRIVER);

            // Step 2: Establish database connection
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // Step 3: Prepare the stored procedure call
            String sql = "{call get_all_cities()}";
            cstmt = conn.prepareCall(sql);

            // Step 4: Execute the procedure & retrieve the ResultSet
            rs = cstmt.executeQuery();

            System.out.println("ID | Name | CountryCode | District | Population");
            System.out.println("-------------------------------------------------");
            while (rs.next()) {
                int id = rs.getInt("ID");
                String name = rs.getString("Name");
                String countryCode = rs.getString("CountryCode");
                String district = rs.getString("District");
                int population = rs.getInt("Population");

                System.out.println(id + " | " + name + " | " + countryCode + " | " + district + " | " + population);
            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            // Step 5: Clean up database resources
            try {
                if (rs != null) rs.close();
                if (cstmt != null) cstmt.close();
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}

Key Steps to Remember

  • Use conn.prepareCall("{call get_all_cities()}") with JDBC escape syntax to invoke the procedure.
  • Because the procedure executes a SELECT query directly, call cstmt.executeQuery() to obtain the resulting ResultSet directly.
  • Iterate through the result rows using while (rs.next()) and standard getter methods.
  • Always close the ResultSet, CallableStatement, and Connection in the finally block to avoid resource leaks.

Related Tutorials You Might Enjoy


Click here to watch in Youtube : https://www.youtube.com/watch?v=iC7J6EFhjZQ&list=UUhwKlOVR041tngjerWxVccw&index=5

Click the below Image to Enlarge
JDBC - CallableStatement (Mysql)
JDBC - CallableStatement (Mysql)
Create Stored Procedure
USE `world`;
DROP procedure IF EXISTS `getAllCities`;

DELIMITER $$
USE `world`$$
CREATE PROCEDURE `getAllCities` ()
BEGIN
  select * from city;
END$$

DELIMITER ;
Call Stored Procedure
call getAllCities();
JDBCCallableStatementDemo.java
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCCallableStatementDemo
{
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/world";

    // Database credentials
    static final String USERNAME = "root";
    static final String PASSWORD = "root";

    public static void main(String[] args)
    {
        JDBCCallableStatementDemo jdbcCallableStatementDemo = new JDBCCallableStatementDemo();

        jdbcCallableStatementDemo.getAllCitiesInfo();

    }

    private void getAllCitiesInfo()
    {
        Connection connection = null;
        CallableStatement callableStatement = null;
        try
        {
            /*
             * Register the JDBC driver in DriverManager
             */

            Class.forName(JDBC_DRIVER);

            /*
             * Establish connection to the Database using DriverManager
             */

            connection = DriverManager
                    .getConnection(DB_URL, USERNAME, PASSWORD);

            String plSql = "{call getAllCities()}";

            /*
             * Creates a CallableStatement object for calling database stored
             * procedures. The CallableStatement object provides methods for
             * setting up its IN and OUT parameters, and methods for executing
             * the call to a stored procedure.
             */

            callableStatement = connection.prepareCall(plSql);
            
            /*
             * Use execute method to run the stored procedure.
             */
            ResultSet rs = callableStatement.executeQuery();

            while (rs.next())
            {
                int id = rs.getInt(1);
                String name = rs.getString(2);
                String countryCode = rs.getString(3);
                String district = rs.getString(4);
                int population = rs.getInt(5);

                /*
                 * Display values
                 */
                System.out.print("ID: " + id);
                System.out.print(", Name: " + name);
                System.out.print(", CountryCode: " + countryCode);
                System.out.print(", District: " + district);
                System.out.println(", Population: " + population);
            }

        }
        catch (SQLException se)
        {
            se.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            /*
             * finally block used to close resources
             */
            try
            {
                if (callableStatement != null)
                {
                    callableStatement.close();
                }
            }
            catch (SQLException sqlException)
            {
                sqlException.printStackTrace();
            }
            try
            {
                if (connection != null)
                {
                    connection.close();
                }
            }
            catch (SQLException sqlException)
            {
                sqlException.printStackTrace();
            }
        }

    }
}

Output
ID: 1, Name: Kabul, CountryCode: AFG, District: Kabol, Population: 1780000
ID: 2, Name: Qandahar, CountryCode: AFG, District: Qandahar, Population: 237500
ID: 3, Name: Herat, CountryCode: AFG, District: Herat, Population: 186800
ID: 4, Name: Mazar-e-Sharif, CountryCode: AFG, District: Balkh, Population: 127800
ID: 5, Name: Amsterdam, CountryCode: NLD, District: Noord-Holland, Population: 50000
ID: 6, Name: Rotterdam, CountryCode: NLD, District: Zuid-Holland, Population: 4000
ID: 7, Name: Haag, CountryCode: NLD, District: Zuid-Holland, Population: 440900
ID: 8, Name: Utrecht, CountryCode: NLD, District: Utrecht, Population: 234323
....
....
To Download JDBCCallableStatementDemoMysqlApp Project Click the below link

https://sites.google.com/site/javaee4321/jdbc/JDBCCallableStatementDemoMysqlApp.zip?attredirects=0&d=1

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • No comments:

    Post a Comment

    Tutorials