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

Friday, 10 July 2015

Oracle : Stored Procedure with Input and Output Parameters

🔔 Enjoying this tutorial?

Subscribe to our channel to learn Java, Oracle DB, SQL, and practical backend programming step-by-step!

▶ Subscribe to Ram N Java

Introduction: What is a Stored Procedure?

A Stored Procedure in Oracle is a precompiled collection of SQL statements and PL/SQL code stored directly inside the database. Instead of executing queries repeatedly from your application, you can execute a stored procedure with parameters to perform database tasks securely and efficiently.

In this guide, you will learn how to create and execute a stored procedure named get_country_name that accepts a Country ID as an IN parameter and returns the corresponding Country Name as an OUT parameter.

Step 1: Defining Input and Output Parameters

When creating a stored procedure in Oracle SQL Developer or a SQL console, parameters define the data flowing in and out:

  • country_id_input (IN): The identifier you pass to search for the country.
  • country_name_output (OUT): The variable that holds and returns the fetched country name.

Step 2: Stored Procedure SQL Logic

Here is the SQL query written inside the body of the procedure to retrieve the value:

SELECT country_name 
INTO country_name_output 
FROM countries 
WHERE country_id = country_id_input;
  

After writing the query, compile the procedure to ensure there are no syntax or semantic errors.

Step 3: Running and Testing the Procedure

Testing the stored procedure in Oracle SQL Developer is straightforward:

  1. Click on the Run button for the procedure.
  2. Enter the input value for country_id_input (e.g., passing a country code).
  3. Execute and inspect the Output Variables tab.
  4. You will see the result returned (such as Argentina or India) in the output field.

Step 4: Dropping the Stored Procedure

If you no longer need the procedure or wish to re-create it from scratch, you can right-click the procedure name in the tree view and select Drop, or execute:

DROP PROCEDURE get_country_name;
  

Click here to watch in Youtube :
https://www.youtube.com/watch?v=QZmZ8hYBJgk&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
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters
Oracle : Stored Procedure with Input and Output Parameters

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
  • Friday, 1 May 2015

    JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle

    🚀 Master Java & Backend Development!

    Subscribe to Ram N Java for clean, beginner-friendly coding tutorials and architecture guides!

    👉 Click Here to Subscribe Now

    What is C3P0 Connection Pooling?

    In high-traffic Java web applications, opening and closing physical database connections repeatedly creates massive performance overhead. C3P0 is an open-source JDBC connection pool library that pre-initializes a pool of reusable connections. When your servlet requires database access, it simply borrows a connection from the pool and returns it when finished, significantly improving response times.

    Step 1: Add Required JAR Files to Tomcat

    To enable Tomcat and your application to use C3P0 with Oracle Database, copy the following JAR files directly into your Tomcat server's lib folder:

    • C3P0 JARs: Download the C3P0 library and place c3p0.jar and mchange-commons-java.jar into Tomcat/lib.
    • Oracle JDBC Driver: Add ojdbc6.jar (or compatible driver) into Tomcat/lib so Tomcat can communicate with Oracle.

    Step 2: Configure the C3P0 DataSource in context.xml

    Define the connection pool resource inside Apache Tomcat's context.xml file so it registers with the JNDI naming service:

    <Resource name="jdbc/hrDB"
      auth="Container"
      type="com.mchange.v2.c3p0.ComboPooledDataSource"
      factory="org.apache.naming.factory.BeanFactory"
      driverClass="oracle.jdbc.OracleDriver"
      jdbcUrl="jdbc:oracle:thin:@localhost:1521:XE"
      user="hr"
      password="hr"
      maxPoolSize="50"
      minPoolSize="10"
      acquireIncrement="10" />

    Step 3: Reference the Resource in web.xml

    Declare the resource reference inside your web application's web.xml deployment descriptor:

    <resource-ref>
      <description>Oracle DB Connection</description>
      <res-ref-name>jdbc/hrDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
    </resource-ref>

    Step 4: Retrieve and Use Connections in the Servlet

    Inside your Servlet's init() method, perform a JNDI lookup to obtain the DataSource. Then, inside doGet(), retrieve a connection from the pool, execute SQL queries, and return output to the client:

    Context initContext = new InitialContext();
    Context envContext = (Context) initContext.lookup("java:comp/env");
    DataSource ds = (DataSource) envContext.lookup("jdbc/hrDB");

    try (Connection conn = ds.getConnection();
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT employee_id, first_name, last_name, email FROM employees")) {
      while (rs.next()) {
        out.println(rs.getInt("employee_id") + " - " + rs.getString("first_name"));
      }
    }

    📺 Related Database & Connection Pooling Tutorials

    Continue enhancing your Java backend knowledge with these related tutorials from our channel:


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

    Click the below Image to Enlarge
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle
    JDBC|Servlets : Tomcat C3PO Connection Pooling - Oracle

    EmployeeInfoServlet.java
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.sql.DataSource;
    
    public class EmployeeInfoServlet extends HttpServlet
    {
    
        private static final long serialVersionUID = 1L;
    
        DataSource                dataSource       = null;
    
        public void init( ServletConfig config )
        {
            try
            {
    
                System.out
                        .println("-----------------------------------------------------");
                System.out
                        .println("init method has been called and servlet is initialized");
    
                /*
                 * Using JDNI lookup get the DataSource.
                 */
    
                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup("java:/comp/env");
                dataSource = (DataSource) envContext.lookup("jdbc/HRDB");
    
                System.out.println("Using JDNI lookup got the DataSource : "
                        + dataSource);
    
                System.out
                        .println("-----------------------------------------------------");
            }
    
            catch( Exception exe )
            {
                exe.printStackTrace();
            }
    
        }
    
        public void doGet( HttpServletRequest request, HttpServletResponse response )
                throws ServletException, IOException
        {
    
            System.out
                    .println("-----------------------------------------------------");
            System.out.println("doGet method has been called");
            System.out
                    .println("-----------------------------------------------------");
    
            response.setContentType("text/html");
    
            PrintWriter out = response.getWriter();
            String title = "Employee Information From Oracle Database";
            out.print("<html><body bgcolor=\"#f0f0f0\">");
            out.print("<h1 align=\"center\">" + title + "</h1>\n");
    
            showEmployeeInformation(out);
    
            out.print("</body></html>");
        }
    
        public void destroy()
        {
            System.out
                    .println("-----------------------------------------------------");
            System.out
                    .println("destroy method has been called and servlet is destroyed");
            System.out
                    .println("-----------------------------------------------------");
        }
    
        private void showEmployeeInformation( PrintWriter out )
        {
            Connection connection = null;
            Statement stmt = null;
            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
                     */
                    out.print("employee_id: " + id+"<br>");
                    out.print("first_name: " + firstName+"<br>");
                    out.print("last_name: " + lastName+"<br>");
                    out.print("email: " + email+"<br>");
                    out.println("phone_number: " + phoneNumber+"<br>");
                    out.println("-------------------------------------------");
                }
                rs.close();
    
            }
    
            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();
                }
            }
    
        }
    
    }
    
    web.xml
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        metadata-complete="true" version="3.0">
        <display-name>EmployeeInfoDemo</display-name>
        <description>
            This is a simple web application with a source code organization
            based on the recommendations of the Application Developer's Guide.
        </description>
        <servlet>
            <servlet-name>employeeInfoServlet</servlet-name>
            <servlet-class>EmployeeInfoServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>employeeInfoServlet</servlet-name>
            <url-pattern>/employeeInfo</url-pattern>
        </servlet-mapping>
    
        <resource-ref>
            <description>DB Connection</description>
            <res-ref-name>jdbc/HRDB</res-ref-name>
            <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
        </resource-ref>
    
    </web-app>
    
    index.html
    <!DOCTYPE HTML><html lang="en"><head>
    <meta charset="UTF-8">
    <title>Employee Information</title>
    </head>
    <body>
    <p>
    <h3>Employee Information</H3>
    <p></p>
    <ul>
    
    <li><a href="employeeInfo">Show Employee Information</a></li>
    
    </ul>
    </body></html>
    
    
    To Download EmployeeInfoDemoTomcatC3POOracleApp Project Click the below link

    https://drive.google.com/file/d/1bnBxzVhyizv_f03BgFrSrSZPhbArVtFB/view

    External Links:

    Download the latest c3p0-{version}.jar from :  http://sourceforge.net/projects/c3p0/

    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • Thursday, 30 April 2015

    JDBC|Servlets : Tomcat Connection Pooling - DBCP- Oracle

    🚀 Master Java, JDBC & Web Technologies!

    Subscribe to Ram N Java for clean, beginner-friendly coding tutorials and architecture guides!

    👉 Click Here to Subscribe Now

    Why Use Tomcat DBCP with Oracle Database?

    Repeatedly opening and tearing down physical database connections in an enterprise application creates significant CPU and network overhead. Apache Tomcat comes pre-configured with Apache Commons DBCP (Database Connection Pooling), allowing web applications to borrow existing, pre-warmed database connections on demand and recycle them back to the pool once requests finish.

    Step 1: Add the Oracle JDBC Driver to Tomcat

    Tomcat already bundles the DBCP library inside its core libraries. To connect to an Oracle Database, you only need to ensure the Oracle JDBC driver is available globally to Tomcat:

    • Place your Oracle JDBC driver JAR (e.g., ojdbc6.jar or ojdbc8.jar) directly into the Tomcat/lib folder.
    • Restart your Apache Tomcat server so it can register the Oracle driver.

    Step 2: Configure DBCP DataSource in context.xml

    Declare your DBCP DataSource resource in the web application's META-INF/context.xml file:

    <Resource name="jdbc/hrDB"
      auth="Container"
      type="javax.sql.DataSource"
      factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
      driverClassName="oracle.jdbc.OracleDriver"
      url="jdbc:oracle:thin:@localhost:1521:XE"
      username="hr"
      password="hr"
      maxTotal="25"
      maxIdle="10"
      minIdle="5"
      maxWaitMillis="10000" />

    Step 3: Reference the Resource in web.xml

    Map the JNDI naming resource inside your application's web.xml deployment descriptor:

    <resource-ref>
      <description>Oracle DBCP Connection Pool</description>
      <res-ref-name>jdbc/hrDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
    </resource-ref>

    Step 4: Perform JNDI Lookup and Query Data in Servlet

    Look up the DataSource via JNDI in your Java Servlet, borrow a connection, and execute your SQL queries:

    Context initContext = new InitialContext();
    Context envContext = (Context) initContext.lookup("java:comp/env");
    DataSource ds = (DataSource) envContext.lookup("jdbc/hrDB");

    try (Connection conn = ds.getConnection();
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT employee_id, first_name, email FROM employees")) {
      while (rs.next()) {
        out.println(rs.getInt("employee_id") + " - " + rs.getString("first_name"));
      }
    }

    📺 Related Oracle & Connection Pooling Tutorials

    Explore more database connectivity and connection pool guides from our channel:

    Friday, 24 April 2015

    Oracle Sql Developer - Connect to the User

    🚀 Master Java & Databases with Ram N Java!

    Subscribe to get clear, beginner-friendly tutorials right when they drop.

    🔔 Subscribe to Ram N Java

    Connecting to Oracle with SQL Developer

    Oracle SQL Developer is a free, integrated development environment that simplifies the development and management of Oracle Database in both traditional and cloud deployments. It offers complete end-to-end development of your PL/SQL applications, a worksheet for running queries and scripts, and a DBA console for managing the database.

    In this tutorial, you will learn how to configure a new database connection inside Oracle SQL Developer and verify communication with your local or remote Oracle instance.

    Step-by-Step Connection Setup

    1. Launch SQL Developer: Open the Oracle SQL Developer application on your system.
    2. Create a New Connection: In the Connections panel on the left, click the green + (plus) icon to open the New / Select Database Connection dialog.
    3. Configure Parameters:
      • Name: Provide a recognizable connection name (e.g., Local_Oracle_XE).
      • Username & Password: Enter your database credentials (such as system or a custom schema user).
      • Connection Type: Select Basic.
      • Role: Leave as default (or choose SYSDBA if logging in as SYS).
      • Hostname: Enter localhost or 127.0.0.1.
      • Port: Default Oracle listener port is 1521.
      • SID / Service Name: Select SID (e.g., xe) or specify your pluggable database Service Name (e.g., xepdb1 or orcl).
    4. Test the Connection: Click the Test button in the lower-left corner. Check the status in the bottom-left area; it should report Success.
    5. Save & Connect: Click Save to store the configuration, then click Connect to open an active SQL worksheet.

    Key Features of Oracle SQL Developer

    • SQL Worksheet: Execute SQL queries, run PL/SQL blocks, and view detailed explain plans.
    • Schema Browser: Visually navigate tables, views, triggers, sequences, and stored packages.
    • Data Export & Import: Export datasets to CSV, Excel, or SQL insert scripts with a few clicks.

    Recommended Next Watch

    Continue expanding your database setup and management expertise with these tutorials:


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

    Click the below Image to Enlarge
    Oracle Sql Developer - Connect to the User
    Oracle Sql Developer - Connect to the User
    Oracle Sql Developer - Connect to the User
    Oracle Sql Developer - Connect to the User
    Oracle Sql Developer - Connect to the User
    Oracle Sql Developer - Connect to the User
    Oracle Sql Developer - Connect to the User
    Oracle Sql Developer - Connect to the User
    Oracle Sql Developer - Connect to the User
    Oracle Sql Developer - Connect to the User
    Oracle Sql Developer - Connect to the User
    Oracle Sql Developer - Connect to the User
    Oracle Sql Developer - Connect to the User
    See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • Oracle Sql Developer Installation

    🚀 Master Java & Databases with Ram N Java!

    Subscribe to get clear, beginner-friendly tutorials right when they drop.

    🔔 Subscribe to Ram N Java

    Setting Up Oracle SQL Developer on Windows

    Oracle SQL Developer is the primary integrated development environment (IDE) provided by Oracle to simplify database administration, SQL querying, and PL/SQL package development. Unlike heavier enterprise tools, SQL Developer is lightweight, portable, and doesn't require a traditional Windows installer setup.

    In this complete walkthrough, you'll learn how to download, extract, configure Java JDK dependencies, and launch Oracle SQL Developer on Windows without errors.

    Step-by-Step Setup Guide

    1. Download Oracle SQL Developer: Go to the official Oracle website and navigate to the SQL Developer downloads page. Choose the Windows 64-bit package (you can choose the one bundled with JDK or download the standalone zip if you already have JDK installed).
    2. Extract the Zip Archive: Extract the downloaded .zip file into a clean directory on your system (such as C:\Program Files\sqldeveloper or C:\sqldeveloper).
    3. Configure Java JDK Path (if prompted): When launching SQL Developer for the first time without bundled Java, specify the path to your installed JDK directory (e.g., C:\Program Files\Java\jdk-xx).
    4. Launch SQL Developer: Double-click sqldeveloper.exe inside the unzipped folder. You can create a desktop shortcut for quick daily access.
    5. Initial Preferences: Choose whether to import preferences from a previous version or start fresh with default settings.

    Why Use Oracle SQL Developer?

    • No Installation Overhead: Fully portable application that runs directly from its extracted directory.
    • Comprehensive Database Management: Manage tables, indexes, views, packages, procedures, triggers, and sequences visually.
    • Rich SQL Worksheet: Features code completion, syntax formatting, SQL execution plans, and script execution tools.

    Recommended Next Watch

    Continue your Oracle Database setup and exploration with these recommended tutorials:


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

    Click here to download Sql Developer:  http://www.oracle.com/technetwork/developer-tools/sql-developer/downloads/sqldev-downloads-403-2292439.html

    Click the below Image to Enlarge
    Oracle Sql Developer Installation
    Oracle Sql Developer Installation
    Oracle Sql Developer Installation
    Oracle Sql Developer Installation
    Oracle Sql Developer Installation
    Oracle Sql Developer Installation
    Oracle Sql Developer Installation
    Oracle Sql Developer Installation
    Oracle Sql Developer Installation
    Oracle Sql Developer Installation
    Oracle Sql Developer Installation
    Oracle Sql Developer Installation
    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • Tutorials