Showing posts with label Oracle DB. Show all posts
Showing posts with label Oracle DB. Show all posts

Wednesday, 15 July 2015

JDBC - CallableStatement Cursor and multiple out param(Oracle)

🚀 Master advanced JDBC, stored procedures, and Oracle database connectivity!

🔔 Subscribe to Ram N Java on YouTube

Why Use JDBC CallableStatement?

In enterprise database applications, business operations and complex SQL queries are frequently encapsulated inside stored procedures and functions residing in the database.

The CallableStatement interface in JDBC is specifically designed to execute database stored procedures. It supports IN parameters (values passed to the procedure), OUT parameters (values returned by the procedure), and even complex types like Oracle SYS_REFCURSOR that return full result sets back to Java.

The Oracle Stored Procedure (GET_COUNTRIES)

Here is the PL/SQL stored procedure that accepts a region ID as an input parameter and returns country data using an Oracle REF CURSOR:

CREATE OR REPLACE PROCEDURE GET_COUNTRIES (
    p_country_cursor OUT SYS_REFCURSOR,
    p_region_id_in   IN  NUMBER
)
AS
BEGIN
    OPEN p_country_cursor FOR
        SELECT country_id, country_name, region_id
        FROM countries
        WHERE region_id = p_region_id_in;
END GET_COUNTRIES;

Java Program: Invoking CallableStatement with Cursors

This complete Java example establishes an Oracle connection, prepares the PL/SQL call, registers the OUT cursor parameter using OracleTypes.CURSOR, and iterates over the returned ResultSet:

package com.ram.jdbc;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
import oracle.jdbc.OracleTypes;

public class JDBCCallableStatementDemo {

    static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
    static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
    static final String USER = "hr";
    static final String PASS = "hr";

    public static void main(String[] args) {
        JDBCCallableStatementDemo demo = new JDBCCallableStatementDemo();
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter Region ID (e.g., 1, 2, 3 or 0 to exit): ");
        int regionId = scanner.nextInt();

        if (regionId > 0) {
            demo.getCountryInformation(regionId);
        }
        scanner.close();
    }

    public void getCountryInformation(int regionId) {
        Connection conn = null;
        CallableStatement cstmt = null;
        ResultSet rs = null;

        try {
            Class.forName(JDBC_DRIVER);
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // Prepare the stored procedure call
            String plsql = "{call GET_COUNTRIES(?, ?)}";
            cstmt = conn.prepareCall(plsql);

            // Register OUT cursor parameter
            cstmt.registerOutParameter(1, OracleTypes.CURSOR);

            // Set IN parameter (Region ID)
            cstmt.setInt(2, regionId);

            // Execute the stored procedure
            cstmt.executeQuery();

            // Retrieve the ResultSet from the cursor parameter
            rs = (ResultSet) cstmt.getObject(1);

            System.out.println("Country ID | Country Name | Region ID");
            System.out.println("----------------------------------------");
            while (rs.next()) {
                String countryId = rs.getString("country_id");
                String countryName = rs.getString("country_name");
                int regId = rs.getInt("region_id");

                System.out.println(countryId + " | " + countryName + " | " + regId);
            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            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 PROCEDURE_NAME(?, ...)}") with curly brace escape syntax.
  • Register OUT parameters using cstmt.registerOutParameter(index, sqlType) before executing.
  • For Oracle REF CURSOR output, register as OracleTypes.CURSOR and cast cstmt.getObject(index) to ResultSet.
  • Always close the ResultSet, CallableStatement, and Connection in the finally block.

Related Tutorials You Might Enjoy


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

Stored Procedure :
create or replace PROCEDURE GET_COUNTRIES
(
  COUNTRY_CURSOR OUT SYS_REFCURSOR,
  REGION_ID_IN IN NUMBER,
  COUNTRY_ID_OUT OUT VARCHAR2, 
  COUNTRY_NAME_OUT OUT VARCHAR2,
  REGION_ID_OUT OUT VARCHAR2  
) AS 
BEGIN
  OPEN COUNTRY_CURSOR FOR 
  SELECT COUNTRY_ID,COUNTRY_NAME,REGION_ID INTO COUNTRY_ID_OUT,COUNTRY_NAME_OUT,REGION_ID_OUT
  FROM COUNTRIES WHERE REGION_ID=REGION_ID_IN;
END GET_COUNTRIES;
Click the below Image to Enlarge
JDBC - CallableStatement Cursor and multiple out param(Oracle) 
JDBC - CallableStatement Cursor and multiple out param(Oracle) 
JDBC - CallableStatement Cursor and multiple out param(Oracle) 

JDBCCallableStatementDemo.java
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

import oracle.jdbc.OracleTypes;

public class JDBCCallableStatementDemo
{
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
    static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";

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

    public static void main(String[] args)
    {
        JDBCCallableStatementDemo jdbcCallableStatementDemo = new JDBCCallableStatementDemo();
        Scanner scanner = new Scanner(System.in);
        while (true)
        {
            System.out.print("Enter the RegionId :");
            int regionId = scanner.nextInt();

            if (regionId == 0)
            {
                break;
            }

            jdbcCallableStatementDemo.getCountryInformation(regionId);

        }
        scanner.close();
    }

    private void getCountryInformation(int regionId)
    {
        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 GET_COUNTRIES(?,?,?,?,?)}";

            callableStatement = connection.prepareCall(plSql);

            /*
             * Bind IN and OUT parameters
             */

            callableStatement.registerOutParameter(1, OracleTypes.CURSOR);
            callableStatement.setInt(2, regionId);
            callableStatement.registerOutParameter(3, java.sql.Types.VARCHAR);
            callableStatement.registerOutParameter(4, java.sql.Types.VARCHAR);
            callableStatement.registerOutParameter(5, java.sql.Types.INTEGER);

            /*
             * Use execute method to run the stored procedure.
             */

            callableStatement.executeQuery();

            ResultSet rs = (ResultSet) callableStatement.getObject(1);

            while (rs.next())
            {
                System.out.print("COUNTRY_ID : " + rs.getString(1));
                System.out.print(", COUNTRY_NAME : " + rs.getString(2));
                System.out.println(", REGION_ID : " + rs.getString(3));
            }

        }
        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
Enter the RegionId :1
COUNTRY_ID : BE, COUNTRY_NAME : Belgium, REGION_ID : 1
COUNTRY_ID : CH, COUNTRY_NAME : Switzerland, REGION_ID : 1
COUNTRY_ID : DE, COUNTRY_NAME : Germany, REGION_ID : 1
COUNTRY_ID : DK, COUNTRY_NAME : Denmark, REGION_ID : 1
COUNTRY_ID : FR, COUNTRY_NAME : France, REGION_ID : 1
COUNTRY_ID : IT, COUNTRY_NAME : Italy, REGION_ID : 1
COUNTRY_ID : NL, COUNTRY_NAME : Netherlands, REGION_ID : 1
COUNTRY_ID : UK, COUNTRY_NAME : United Kingdom, REGION_ID : 1
Enter the RegionId :2
COUNTRY_ID : AR, COUNTRY_NAME : Argentina, REGION_ID : 2
COUNTRY_ID : BR, COUNTRY_NAME : Brazil, REGION_ID : 2
COUNTRY_ID : CA, COUNTRY_NAME : Canada, REGION_ID : 2
COUNTRY_ID : MX, COUNTRY_NAME : Mexico, REGION_ID : 2
COUNTRY_ID : US, COUNTRY_NAME : United States of America, REGION_ID : 2
Enter the RegionId :0
To Download JDBCCallableStatementDemoOracleCursorMultiOutApp Project Click the below link
https://sites.google.com/site/javaee4321/jdbc/JDBCCallableStatementDemoOracleCursorMultiOutApp.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
  • JAVA Tutorial
  • Tuesday, 14 July 2015

    JDBC - CallableStatement Cursor(Oracle)

    🚀 Master advanced JDBC, Oracle database connectivity, and stored procedures!

    🔔 Subscribe to Ram N Java on YouTube

    Why Use Oracle Cursors with JDBC CallableStatement?

    When working with Oracle databases in enterprise Java applications, database logic is often packaged inside PL/SQL stored procedures. Instead of returning a single scalar value, stored procedures can return tabular data via an Oracle SYS_REFCURSOR.

    Using the JDBC CallableStatement interface, Java applications can execute stored procedures that open a cursor and return complete result sets back to Java for processing.

    The PL/SQL Stored Procedure (GET_ALL_COUNTRIES)

    Here is the Oracle stored procedure definition that opens a reference cursor to fetch all rows from the COUNTRIES table:

    CREATE OR REPLACE PROCEDURE GET_ALL_COUNTRIES (
        p_country_cursor OUT SYS_REFCURSOR
    )
    AS
    BEGIN
        OPEN p_country_cursor FOR
            SELECT country_id, country_name, region_id
            FROM countries;
    END GET_ALL_COUNTRIES;

    Complete Java Code Example

    The following Java program connects to an Oracle database, prepares the callable procedure call, registers the OUT cursor parameter with OracleTypes.CURSOR, and reads records into a standard ResultSet:

    package com.ram.jdbc;
    
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import oracle.jdbc.OracleTypes;
    
    public class JDBCCallableStatementDemo {
    
        static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
        static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
        static final String USER = "hr";
        static final String PASS = "hr";
    
        public static void main(String[] args) {
            JDBCCallableStatementDemo demo = new JDBCCallableStatementDemo();
            demo.getAllCountryInformation();
        }
    
        public void getAllCountryInformation() {
            Connection conn = null;
            CallableStatement cstmt = null;
            ResultSet rs = null;
    
            try {
                // Step 1: Register Oracle JDBC Driver
                Class.forName(JDBC_DRIVER);
    
                // Step 2: Establish connection
                conn = DriverManager.getConnection(DB_URL, USER, PASS);
    
                // Step 3: Prepare the procedure call
                String plsql = "{call GET_ALL_COUNTRIES(?)}";
                cstmt = conn.prepareCall(plsql);
    
                // Step 4: Register the OUT parameter as an Oracle cursor
                cstmt.registerOutParameter(1, OracleTypes.CURSOR);
    
                // Step 5: Execute stored procedure
                cstmt.executeQuery();
    
                // Step 6: Extract ResultSet from the OUT cursor parameter
                rs = (ResultSet) cstmt.getObject(1);
    
                System.out.println("Country ID | Country Name | Region ID");
                System.out.println("----------------------------------------");
                while (rs.next()) {
                    String countryId = rs.getString("country_id");
                    String countryName = rs.getString("country_name");
                    int regionId = rs.getInt("region_id");
    
                    System.out.println(countryId + " | " + countryName + " | " + regionId);
                }
    
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            } finally {
                // Step 7: Clean up resources
                try {
                    if (rs != null) rs.close();
                    if (cstmt != null) cstmt.close();
                    if (conn != null) conn.close();
                } catch (SQLException se) {
                    se.printStackTrace();
                }
            }
        }
    }

    Key Steps Explained

    • conn.prepareCall("{call GET_ALL_COUNTRIES(?)}"): Uses JDBC procedure escape syntax to prepare the call with a placeholder for the OUT cursor parameter.
    • cstmt.registerOutParameter(1, OracleTypes.CURSOR): Instructs JDBC that parameter 1 will return an Oracle reference cursor.
    • (ResultSet) cstmt.getObject(1): Casts the returned cursor object directly to a ResultSet, allowing you to iterate through rows seamlessly.
    • The finally block guarantees proper cleanup of the ResultSet, CallableStatement, and Connection.

    Related Tutorials You Might Enjoy


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

    Stored Procedure:
    create or replace 
    PROCEDURE GET_ALL_COUNTRIES 
    (
       country_cursor OUT SYS_REFCURSOR
    ) AS 
    BEGIN
      OPEN country_cursor FOR 
       SELECT * FROM COUNTRIES ;
    END GET_ALL_COUNTRIES;
    
    Click the below Image to Enlarge
    JDBC - CallableStatement Cursor(Oracle)
    JDBC - CallableStatement Cursor(Oracle)
    JDBC - CallableStatement Cursor(Oracle)

    JDBCCallableStatementDemo.java
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import oracle.jdbc.OracleTypes;
    
    public class JDBCCallableStatementDemo
    {
        // JDBC driver name and database URL
        static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
        static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
    
        // Database credentials
        static final String USERNAME = "hr";
        static final String PASSWORD = "hr";
    
        public static void main(String[] args)
        {
            JDBCCallableStatementDemo jdbcCallableStatementDemo = new JDBCCallableStatementDemo();
            jdbcCallableStatementDemo.getAllCountryInformation();
        }
    
        private void getAllCountryInformation()
        {
            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 GET_ALL_COUNTRIES(?)}";
    
                callableStatement = connection.prepareCall(plSql);
                
                callableStatement.registerOutParameter(1,  OracleTypes.CURSOR);
    
                /*
                 * Use execute method to run the stored procedure.
                 */
    
                callableStatement.executeQuery();
    
                ResultSet rs=(ResultSet)callableStatement.getObject(1);
                
                while(rs.next())
                {
                    System.out.print("COUNTRY_ID : "+rs.getString(1));
                    System.out.print(", COUNTRY_NAME : "+rs.getString(2));
                    System.out.println(", REGION_ID : "+rs.getString(3));
                }
    
            }
            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
    COUNTRY_ID : AR, COUNTRY_NAME : Argentina, REGION_ID : 2
    COUNTRY_ID : AU, COUNTRY_NAME : Australia, REGION_ID : 3
    COUNTRY_ID : BE, COUNTRY_NAME : Belgium, REGION_ID : 1
    COUNTRY_ID : BR, COUNTRY_NAME : Brazil, REGION_ID : 2
    COUNTRY_ID : CA, COUNTRY_NAME : Canada, REGION_ID : 2
    COUNTRY_ID : CH, COUNTRY_NAME : Switzerland, REGION_ID : 1
    COUNTRY_ID : CN, COUNTRY_NAME : China, REGION_ID : 3
    COUNTRY_ID : DE, COUNTRY_NAME : Germany, REGION_ID : 1
    COUNTRY_ID : DK, COUNTRY_NAME : Denmark, REGION_ID : 1
    COUNTRY_ID : EG, COUNTRY_NAME : Egypt, REGION_ID : 4
    COUNTRY_ID : FR, COUNTRY_NAME : France, REGION_ID : 1
    COUNTRY_ID : IL, COUNTRY_NAME : Israel, REGION_ID : 4
    COUNTRY_ID : IN, COUNTRY_NAME : India, REGION_ID : 3
    COUNTRY_ID : IT, COUNTRY_NAME : Italy, REGION_ID : 1
    COUNTRY_ID : JP, COUNTRY_NAME : Japan, REGION_ID : 3
    COUNTRY_ID : KW, COUNTRY_NAME : Kuwait, REGION_ID : 4
    COUNTRY_ID : ML, COUNTRY_NAME : Malaysia, REGION_ID : 3
    COUNTRY_ID : MX, COUNTRY_NAME : Mexico, REGION_ID : 2
    COUNTRY_ID : NG, COUNTRY_NAME : Nigeria, REGION_ID : 4
    COUNTRY_ID : NL, COUNTRY_NAME : Netherlands, REGION_ID : 1
    COUNTRY_ID : SG, COUNTRY_NAME : Singapore, REGION_ID : 3
    COUNTRY_ID : UK, COUNTRY_NAME : United Kingdom, REGION_ID : 1
    COUNTRY_ID : US, COUNTRY_NAME : United States of America, REGION_ID : 2
    COUNTRY_ID : ZM, COUNTRY_NAME : Zambia, REGION_ID : 4
    COUNTRY_ID : ZW, COUNTRY_NAME : Zimbabwe, REGION_ID : 4
    
    To Download JDBCCallableStatementDemoOracleCursorApp Project Click the below link
    https://sites.google.com/site/javaee4321/jdbc/JDBCCallableStatementDemoOracleCursorApp.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
  • JAVA Tutorial
  • Monday, 13 July 2015

    JDBC - CallableStatement In Out Parameters (Oracle)

    🚀 Master Java database programming and Oracle stored procedures!

    🔔 Subscribe to Ram N Java on YouTube

    What Is CallableStatement in JDBC?

    In Java Database Connectivity (JDBC), the CallableStatement interface extends PreparedStatement and is specifically designed to execute database stored procedures and stored functions.

    Stored procedures often require input data to perform operations and return calculated results back to the caller. With CallableStatement, you can easily bind IN parameters and register OUT parameters to fetch values directly into your Java application.

    The Oracle Stored Procedure (GET_COUNTRY_NAME)

    Below is the PL/SQL stored procedure created in the Oracle database. It takes a country ID as an input parameter (IN) and retrieves the corresponding country name into an output parameter (OUT):

    CREATE OR REPLACE PROCEDURE GET_COUNTRY_NAME (
        country_id_input    IN  VARCHAR2,
        country_name_output OUT VARCHAR2
    )
    AS
    BEGIN
        SELECT country_name
        INTO country_name_output
        FROM countries
        WHERE country_id = country_id_input;
    END GET_COUNTRY_NAME;

    Complete Java Source Code

    The following Java program connects to an Oracle database, prepares the stored procedure call, binds the user input, registers the return parameter, and prints the result:

    package com.ram.jdbc;
    
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Types;
    import java.util.Scanner;
    
    public class JDBCCallableStatementDemo {
    
        static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
        static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
        static final String USER = "hr";
        static final String PASS = "hr";
    
        public static void main(String[] args) {
            JDBCCallableStatementDemo demo = new JDBCCallableStatementDemo();
            Scanner scanner = new Scanner(System.in);
    
            System.out.print("Enter Country ID (e.g., AR, IN, US) or 'exit': ");
            String countryId = scanner.next();
    
            while (!"exit".equalsIgnoreCase(countryId)) {
                demo.getCountryName(countryId);
    
                System.out.print("\nEnter Country ID or 'exit': ");
                countryId = scanner.next();
            }
            scanner.close();
        }
    
        public void getCountryName(String countryId) {
            Connection conn = null;
            CallableStatement cstmt = null;
    
            try {
                // Step 1: Register Oracle JDBC Driver
                Class.forName(JDBC_DRIVER);
    
                // Step 2: Establish connection
                conn = DriverManager.getConnection(DB_URL, USER, PASS);
    
                // Step 3: Prepare the procedure call with escape syntax
                String plsql = "{call GET_COUNTRY_NAME(?, ?)}";
                cstmt = conn.prepareCall(plsql);
    
                // Step 4: Bind the IN parameter (Country ID)
                cstmt.setString(1, countryId);
    
                // Step 5: Register the OUT parameter type
                cstmt.registerOutParameter(2, Types.VARCHAR);
    
                // Step 6: Execute procedure
                cstmt.execute();
    
                // Step 7: Retrieve the OUT parameter value
                String countryName = cstmt.getString(2);
                System.out.println("Country Name: " + countryName);
    
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            } finally {
                // Step 8: Clean up database resources
                try {
                    if (cstmt != null) cstmt.close();
                    if (conn != null) conn.close();
                } catch (SQLException se) {
                    se.printStackTrace();
                }
            }
        }
    }

    Key Steps in Using CallableStatement

    • Call Syntax: Use the standard SQL escape format: "{call PROCEDURE_NAME(?, ?)}".
    • Bind Inputs: Set input parameter values using standard setter methods like setString() or setInt().
    • Register Output Types: Use registerOutParameter(index, java.sql.Types.VARCHAR) before invoking the procedure.
    • Read Outputs: After calling execute(), fetch the resulting values using appropriate getter methods like getString(index).

    Related Tutorials You Might Enjoy


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

    Stored Procedure :
    CREATE OR REPLACE PROCEDURE GET_COUNTRY_NAME 
    (
      COUNTRY_ID_INPUT IN VARCHAR2 
    , COUNTRY_NAME_OUTPUT OUT VARCHAR2 
    ) AS 
    BEGIN
      SELECT COUNTRY_NAME INTO COUNTRY_NAME_OUTPUT FROM COUNTRIES WHERE COUNTRY_ID=COUNTRY_ID_INPUT;
    END GET_COUNTRY_NAME;
    

    Click the below Image to Enlarge
    JDBC - CallableStatement In Out Parameters (Oracle) 
    JDBC - CallableStatement In Out Parameters (Oracle) 
    JDBC - CallableStatement In Out Parameters (Oracle) 

    JDBCCallableStatementDemo.java
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.Scanner;
    
    public class JDBCCallableStatementDemo
    {
        // JDBC driver name and database URL
        static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
        static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
    
        // Database credentials
        static final String USERNAME = "hr";
        static final String PASSWORD = "hr";
    
        public static void main(String[] args)
        {
            JDBCCallableStatementDemo jdbcCallableStatementDemo = new JDBCCallableStatementDemo();
    
            Scanner scanner = new Scanner(System.in);
            while (true)
            {
                System.out.print("Enter the CountryId :");
                String countryId = scanner.nextLine();
    
                if (countryId.equals("exit"))
                {
                    break;
                }
    
                jdbcCallableStatementDemo.getCountryName(countryId);
    
            }
            scanner.close();
        }
    
        private void getCountryName(String countryId)
        {
            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 GET_COUNTRY_NAME(?,?)}";
    
                callableStatement = connection.prepareCall(plSql);
    
                /*
                 * Bind IN parameter first, then bind OUT parameters
                 */
    
                callableStatement.setString(1, countryId);
    
                /*
                 * Register OUT Parameters
                 */
                callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR);
    
                /*
                 * Use execute method to run the stored procedure.
                 */
    
                callableStatement.execute();
    
                /*
                 * Retrieve countryName with getXXX method
                 */
                String countryName = callableStatement.getString(2);
    
                System.out.println("countryName : " + countryName);
    
            }
            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
    Enter the CountryId :AR
    countryName : Argentina
    Enter the CountryId :IN
    countryName : India
    Enter the CountryId :exit
    
    To Download JDBCCallableStatementDemoOracleINOUTApp Project Click the below link
    https://sites.google.com/site/javaee4321/jdbc/JDBCCallableStatementDemoOracleINOUTApp.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
  • JAVA Tutorial
  • Oracle : Stored Procedure Cursor

    Master Java & Oracle Database!

    Subscribe to Ram N Java for hands-on JDBC tutorials, practical database scripts, and clear step-by-step coding guides.

    SUBSCRIBE NOW

    Overview: Returning Result Sets from Oracle Stored Procedures

    In Oracle Database, stored procedures do not automatically return result sets like standard SQL queries or MySQL procedures. Instead, Oracle uses SYS_REFCURSOR (cursor reference) to stream multiple records back to the calling client application.

    Using JDBC and the CallableStatement interface, Java applications can easily register an OUT parameter of type cursor, execute the procedure, and read the rows into a standard Java ResultSet.

    Step 1: The Oracle Stored Procedure

    To return all rows from a COUNTRY table, define an Oracle stored procedure that accepts a cursor as an OUT parameter:

    CREATE OR REPLACE PROCEDURE get_all_countries(
        p_cursor OUT SYS_REFCURSOR
    ) AS
    BEGIN
        OPEN p_cursor FOR
            SELECT country_id, country_name, region_id FROM countries;
    END;
    /

    Step 2: Invoking the Procedure via JDBC

    In Java, register the cursor output parameter using Oracle's cursor data type definition (OracleTypes.CURSOR), execute the procedure, and cast the returned object into a standard ResultSet:

    String sql = "{call get_all_countries(?)}";
    CallableStatement cstmt = connection.prepareCall(sql);
    
    // Register cursor OUT parameter
    cstmt.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR);
    
    // Execute procedure
    cstmt.execute();
    
    // Retrieve records into ResultSet
    ResultSet rs = (ResultSet) cstmt.getObject(1);
    while (rs.next()) {
        System.out.println("ID: " + rs.getString("country_id") + 
                           ", Name: " + rs.getString("country_name"));
    }

    Why Use Ref Cursors in Oracle?

    • Encapsulated Query Logic: SQL query definitions stay managed inside the database catalog rather than hard-coded into Java application layers.
    • Optimal Resource Consumption: Cursors stream records efficiently without buffering large datasets entirely in database memory.
    • Seamless Integration: Fits naturally into standard JDBC ResultSet iterations for developer productivity.

    Recommended Oracle & CallableStatement Tutorials

    Continue mastering Oracle database connectivity with these related tutorials from our channel:

    Friday, 12 September 2014

    JDBC DBCP DataSource - Oracle

    🚀 Master Java database programming, connection pooling, and Oracle JDBC!

    🔔 Subscribe to Ram N Java on YouTube

    What Is Apache Commons DBCP DataSource?

    Opening and closing physical database connections directly via DriverManager for every client request creates significant CPU and network overhead. In enterprise applications, connection pooling is used to manage and reuse a pool of active database connections.

    Apache Commons DBCP (Database Connection Pool) provides the BasicDataSource class (from org.apache.commons.dbcp), which implements javax.sql.DataSource. It encapsulates database credentials and connection parameters, efficiently maintaining a pool of pre-established connections for reuse.

    Required Dependencies

    To use DBCP connection pooling in your Java project, ensure the following JAR files are present on your classpath:

    • commons-dbcp.jar
    • commons-pool.jar
    • ojdbc.jar (Oracle JDBC Driver)

    Complete Java Source Code Example

    The following Java program creates and configures a BasicDataSource, gets a connection from the pool, queries the Oracle EMPLOYEES table in the HR schema, and displays employee records:

    package com.ram.jdbc;
    
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.sql.DataSource;
    import org.apache.commons.dbcp.BasicDataSource;
    
    public class DBCPDataSourceDemo {
    
        static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
        static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
        static final String USER = "hr";
        static final String PASS = "hr";
    
        // Method to create and configure the BasicDataSource instance
        public static DataSource getDataSource() {
            BasicDataSource ds = new BasicDataSource();
            ds.setDriverClassName(JDBC_DRIVER);
            ds.setUrl(DB_URL);
            ds.setUsername(USER);
            ds.setPassword(PASS);
            return ds;
        }
    
        public static void main(String[] args) {
            Connection conn = null;
            Statement stmt = null;
            ResultSet rs = null;
    
            try {
                // Obtain DataSource
                DataSource dataSource = getDataSource();
    
                // Borrow connection from DBCP pool
                conn = dataSource.getConnection();
    
                stmt = conn.createStatement();
                String sql = "SELECT employee_id, first_name, last_name, email, phone_number FROM employees";
                rs = stmt.executeQuery(sql);
    
                System.out.println("ID | Name | Email | Phone");
                System.out.println("----------------------------------------");
                while (rs.next()) {
                    int empId = rs.getInt("employee_id");
                    String firstName = rs.getString("first_name");
                    String lastName = rs.getString("last_name");
                    String email = rs.getString("email");
                    String phone = rs.getString("phone_number");
    
                    System.out.println(empId + " | " + firstName + " " + lastName + " | " + email + " | " + phone);
                }
    
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                // Clean up resources (closing connection returns it back to the pool)
                try {
                    if (rs != null) rs.close();
                    if (stmt != null) stmt.close();
                    if (conn != null) conn.close();
                } catch (SQLException se) {
                    se.printStackTrace();
                }
            }
        }
    }

    Key Steps & Best Practices

    • Configure BasicDataSource: Set the driver class name, JDBC URL, username, and password via setter methods on BasicDataSource.
    • Program to Interfaces: Keep the return type as standard javax.sql.DataSource to decouple application code from specific connection pooling libraries.
    • Connection Recycling: Calling conn.close() on a pooled connection does not terminate the physical database link; it returns the connection back to the DBCP pool for reuse.
    • Always ensure ResultSet, Statement, and Connection are closed in a finally block to avoid connection starvation in the pool.

    Related Tutorials You Might Enjoy


    Click here to watch in Youtube : https://www.youtube.com/watch?v=s_h54qI0npE


    Click the below Image to Enlarge
    JDBC DBCP DataSource - Oracle
    JDBC DBCP DataSource - Oracle
    JDBC DBCP DataSource - Oracle

    DbcpBasicDataSource.java
    import javax.sql.DataSource;
    
    import org.apache.commons.dbcp2.BasicDataSource;
    
    public class DbcpBasicDataSource
    {
    
        public static DataSource getDbcpBasicDataSource()
        {
    
            BasicDataSource basicDataSource = new BasicDataSource();
            try
            {
                basicDataSource.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
                basicDataSource.setUsername("hr");
                basicDataSource.setPassword("hr");
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
            return basicDataSource;
        }
    
        
    }
    
    JDBCDataSourceDemo.java
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    import javax.sql.DataSource;
    
    public class JDBCDataSourceDemo
    {
    
        public static void main( String[] args )
        {
            JDBCDataSourceDemo jdbcDataSourceDemo = new JDBCDataSourceDemo();
            jdbcDataSourceDemo.getEmployeeInformation();
    
        }
    
        private void getEmployeeInformation()
        {
            Connection connection = null;
            Statement stmt = null;
            /*
             * Get the dbcp2 BasicDataSource
             */
            DataSource dataSource = DbcpBasicDataSource.getDbcpBasicDataSource();
            try
            {
                /*
                 *  Get connection from the DataSource
                 */
                connection = dataSource.getConnection();
                
                /*
                 *  Execute the Query
                 */
                
                stmt = connection.createStatement();
                String sql = "select employee_id,first_name,last_name,email,phone_number from employees";
                ResultSet rs = stmt.executeQuery(sql);
    
                /*
                 *  Iterate the ResultSet and get each row
                 *  Information.
                 */
                while( rs.next() )
                {
                    /*
                     * Retrieve by column name
                     */
                    int id = rs.getInt("employee_id");
                    String firstName = rs.getString("first_name");
                    String lastName = rs.getString("last_name");
                    String email = rs.getString("email");
                    String phoneNumber = rs.getString("phone_number");
    
                    /*
                     * Display values
                     */
                    System.out.print("employee_id: " + id);
                    System.out.print(", first_name: " + firstName);
                    System.out.print(", last_name: " + lastName);
                    System.out.print(", email: " + email);
                    System.out.println(", phone_number: " + phoneNumber);
                }
                rs.close();     
            }
            catch( SQLException se )
            {
                se.printStackTrace();
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
    
            finally
            {
                /*
                 * finally block used to close resources
                 */
                try
                {
                    if( stmt != null )
                    {
                        stmt.close();
                    }
                }
                catch( SQLException sqlException )
                {
                    sqlException.printStackTrace();
                }
                try
                {
                    if( connection != null )
                    {
                        connection.close();
                    }
                }
                catch( SQLException sqlException )
                {
                    sqlException.printStackTrace();
                }
    
            }
    
        }
    }
    
    
    Output
    employee_id: 100, first_name: Steven, last_name: King, email: SKING, phone_number: 515.123.4567
    employee_id: 101, first_name: Neena, last_name: Kochhar, email: NKOCHHAR, phone_number: 515.123.4568
    employee_id: 102, first_name: Lex, last_name: De Haan, email: LDEHAAN, phone_number: 515.123.4569
    employee_id: 103, first_name: Alexander, last_name: Hunold, email: AHUNOLD, phone_number: 590.423.4567
    employee_id: 104, first_name: Bruce, last_name: Ernst, email: BERNST, phone_number: 590.423.4568
    employee_id: 105, first_name: David, last_name: Austin, email: DAUSTIN, phone_number: 590.423.4569
    employee_id: 106, first_name: Valli, last_name: Pataballa, email: VPATABAL, phone_number: 590.423.4560
    employee_id: 107, first_name: Diana, last_name: Lorentz, email: DLORENTZ, phone_number: 590.423.5567
    employee_id: 108, first_name: Nancy, last_name: Greenberg, email: NGREENBE, phone_number: 515.124.4569
    
    ---
    ---
    
    Environment Used 

    JDK version : 1.7.0_51
    Oracle 11g

    To Download JDBCDataSourceDemo-DBCP-Oracle Project Click the below link

    https://sites.google.com/site/javaee4321/jdbc/JDBCDataSourceDemo-DBCP-Oracle.zip?attredirects=0&d=1

    External Links

    http://commons.apache.org/proper/commons-dbcp/apidocs/org/apache/commons/dbcp2/BasicDataSource.html

    http://commons.apache.org/

    http://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi

    http://commons.apache.org/proper/commons-pool/download_pool.cgi

    http://commons.apache.org/proper/commons-logging/download_logging.cgi

    See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Older Posts Home

    Tutorials