Skip to main content

How to Call a Stored Procedure by JDBC Java Class?

--
A Stored procedure can return result sets, you can use getResultSet method in the CallableStatement class to retrieve return result sets. When a procedure has return value for an OUT parameter, you must tell the JDBC driver what SQL type the value will be, with the registerOutParameter method. To call stored procedures, you invoke methods in the CallableStatement class. The basic steps are:
  • Creating a CallableStatement object by calling the Connection.prepareCall method.
  • Using the CallableStatement.setXXX methods to pass values to the input (IN) parameters.
  • Using the CallableStatement.registerOutParameter method to indicate which parameters are output-only (OUT) parameters, or input and output (INOUT) parameters.
  • Invoke one of the following methods to call the stored procedure:
    • CallableStatement.executeUpdate method, if the stored procedure does not return result sets.
    • CallableStatement.executeQuery method, if the stored procedure returns one result set.
    • CallableStatement.execute method, if the stored procedure returns multiple result sets.
  • Calling the CallableStatement.getResultSet method to obtain the result set (which is in a ResultSet object), if the stored procedure returns one result set. But if the stored procedure returns result sets, retrieve the result sets by combining CallableStatement.getResultSet and CallableStatement.getMoreResults methods.
  • Using the CallableStatement.getXXX methods to retrieve values from the OUT parameters or INOUT parameters.
  • Calling the CallableStatement.close method to close the CallableStatement object when you have finished using that object.
This example demonstrates how to call stored procedures with IN and OUT parameters in JDBC.
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;

public class JDBCCallProcedure {

    private static final String DBURL = "jdbc:mysql://localhost:3306/mydb?" +
                    "user=usr&password=sql&useUnicode=true" +
                   "&characterEncoding=UTF-8";"
    private static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
  
    static {
        try {
            Class.forName(DBDRIVER).newInstance();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    private static Connection getConnection() 
    {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(DBURL);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void createEmployees()
    {
        Connection con = getConnection();
        Statement stmt =null;
        String createString;
        createString = "CREATE TABLE  `mydb`.`employees` ("+
         "`EmployeeID` int(10) unsigned NOT NULL default '0',"+
         "`Name` varchar(45) collate utf8_unicode_ci NOT NULL default '',"+
         "`Office` varchar(10) collate utf8_unicode_ci NOT NULL default '',"+
         "`CreateTime` timestamp NOT NULL default CURRENT_TIMESTAMP,"+
         "PRIMARY KEY  (`EmployeeID`)"+
         ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";            
        try {
            stmt = con.createStatement();
            stmt.executeUpdate(createString);
        } catch(SQLException ex) {
            System.err.println("SQLException: " + ex.getMessage());
        }
        finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    System.err.println("SQLException: " + e.getMessage());
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    System.err.println("SQLException: " + e.getMessage());
                }
            }
        }
    }
    private static void dropEmployees()
    {
        Connection con = getConnection();
        Statement stmt =null;
        String createString;
        createString = "DROP TABLE IF EXISTS `mydb`.`employees`;";            
        try {
            stmt = con.createStatement();
            stmt.executeUpdate(createString);
        } catch(SQLException ex) {
            System.err.println("SQLException: " + ex.getMessage());
        }
        finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    System.err.println("SQLException: " + e.getMessage());
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    System.err.println("SQLException: " + e.getMessage());
                }
            }
        }
    }
    
    private static void insertEmployee() 
    {
        Connection con = getConnection();
        PreparedStatement ps = null;

        try {
            ps = con.prepareStatement("INSERT INTO Employees(
                    EmployeeID, name, Office) VALUES (?, ?, ?)");
            ps.setInt(1, 1000);
            ps.setString(2, "David Walker");
            ps.setString(3, "HQ101");
            ps.executeUpdate();
            ps.clearParameters();
            ps.setInt(1, 1001);
            ps.setString(2, "Paul Martin");
            ps.setString(3, "HQ101");
            ps.executeUpdate();
        } catch (SQLException e) {
            System.err.println("SQLException: " + e.getMessage());
        }
        finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    System.err.println("SQLException: " + e.getMessage());
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    System.err.println("SQLException: " + e.getMessage());
                }
            }
        }
    }
    
    private    static void createProcedure() {
        Connection con = getConnection();
        Statement stmt =null;
        try {
            stmt = con.createStatement();
            stmt.execute("CREATE PROCEDURE `WhoAreThey`(" +
                       "OUT error VARCHAR(128)," +
                       "IN office VARCHAR(10)) " +
                       "BEGIN "+
                       "SET error = NULL; "+
                       "IF office IS NULL THEN "+
                       "SET error = 'You need to pass in an office number'; 
                       + "ELSE "+
                       "  SELECT EmployeeID, Name " + 
                             " FROM employees WHERE office = office; "+
                       "END IF; "+
                       "END");

           } catch(SQLException ex) {
            System.err.println("SQLException: " + ex.getMessage());
        }
        finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    System.err.println("SQLException: " + e.getMessage());
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    System.err.println("SQLException: " + e.getMessage());
                }
            }
        }
        
    }
    private    static void dropProcedure() {
        Connection con = getConnection();
        Statement stmt =null;
        try {
            stmt = con.createStatement();
            stmt.execute(
                 "DROP PROCEDURE IF EXISTS `mydb`.`WhoAreThey`");
           } catch(SQLException ex) {
            System.err.println("SQLException: " + ex.getMessage());
        }
        finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    System.err.println("SQLException: " + e.getMessage());
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    System.err.println("SQLException: " + e.getMessage());
                }
            }
        }
        
    }
    private    static void callProcedure(String office) {
        Connection con = getConnection();
        CallableStatement cs = null;
        try {
            cs = con.prepareCall("{call WhoAreThey(?,?)}");
            cs.registerOutParameter(1, Types.VARCHAR);
            cs.setString(2, office);
            cs.execute();
            String str = cs.getString(1);
            if (str != null) {
                System.out.println(str);
            }
            else {
                ResultSet rs = cs.getResultSet();
                while (rs.next()) {
                    System.out.println("Name : " + rs.getString(2));
                }
            }
        } catch (SQLException e) {
            System.err.println("SQLException: " + e.getMessage());
        }
        finally {
            if (cs != null) {
                try {
                    cs.close();
                } catch (SQLException e) {
                    System.err.println("SQLException: " + e.getMessage());
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    System.err.println("SQLException: " + e.getMessage());
                }
            }
        }
    }
    public static void main(String[] args) {
        createEmployees();
        insertEmployee();
        createProcedure();
        System.out.println("The first Call ...");
        callProcedure("HQ101");
        System.out.println("The second Call ...");
        callProcedure(null);
        dropProcedure();
        dropEmployees();
    }

}

Comments

Popular posts from this blog

Advantages & Disadvantages of Synchronous / Asynchronous Communications?

  Asynchronous Communication Advantages: Requests need not be targeted to specific server. Service need not be available when request is made. No blocking, so resources could be freed.  Could use connectionless protocol Disadvantages: Response times are unpredictable. Error handling usually more complex.  Usually requires connection-oriented protocol.  Harder to design apps Synchronous Communication Advantages: Easy to program Outcome is known immediately  Error recovery easier (usually)  Better real-time response (usually) Disadvantages: Service must be up and ready. Requestor blocks, held resources are “tied up”.  Usually requires connection-oriented protocol

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag

XML Binding with JAXB 2.0 - Tutorial

Java Architecture for XML Binding (JAXB) is an API/framework that binds XML schema to Java representations. Java objects may then subsequently be used to marshal or unmarshal XML documents. Marshalling an XML document means creating an XML document from Java objects. Unmarshalling means creating creating a Java representation of an XML document (or, in effect, the reverse of marshaling). You retrieve the element and attribute values of the XML document from the Java representation. The JAXB 2.0 specification is implemented in JWSDP 2.0. JAXB 2.0 has some new features, which facilitate the marshalling and unmarshalling of an XML document. JAXB 2.0 also allows you to map a Java object to an XML document or an XML Schema. Some of the new features in JAXB 2.0 include: Smaller runtime libraries are required for JAXB 2.0, which require lesser runtime memory. Significantly, fewer Java classes are generated from a schema, compared to JAXB 1.0. For each top-level complexType, 2.0 generates a v