JDBC Tutorial - JDBC Stored Procedure In Parameter








The following example shows how to call a stored procedure with in parameters.

A stored procedure for Oracle written in PL/SQL is listed below. It inserts a row to Person table. The parameters in the procedure are all marked with IN as input parameters.

CREATE OR REPLACE PROCEDURE insertPERSON(
     p_userid IN PERSON.USER_ID%TYPE,
     p_username IN PERSON.USERNAME%TYPE,
     p_createdby IN PERSON.CREATED_BY%TYPE,
     p_date IN PERSON.CREATED_DATE%TYPE)
IS
BEGIN

  INSERT INTO PERSON ("USER_ID", "USERNAME", "CREATED_BY", "CREATED_DATE") 
  VALUES (p_userid, p_username,p_createdby, p_date);

  COMMIT;

END;
/




Example

The following code creates a CallableStatement from Connection and passes in the name of the stored procedure.

The parameters for the stored procedure are all marked with question marks.

Then the parameters is set to a value with setXXX method from CallableStatement.

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
//from w  w  w .  j  a  va 2  s . co  m
public class Main {
  private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
  private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:YourDatabase";
  private static final String DB_USER = "user";
  private static final String DB_PASSWORD = "password";

  public static void main(String[] argv) throws Exception {
    Class.forName(DB_DRIVER);
    Connection dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER,
        DB_PASSWORD);

    CallableStatement callableStatement = null;
    String insertStoreProc = "{call insertPERSON(?,?,?,?)}";

    java.util.Date today = new java.util.Date();
    callableStatement = dbConnection.prepareCall(insertStoreProc);
    callableStatement.setInt(1, 1000);
    callableStatement.setString(2, "name");
    callableStatement.setString(3, "system");
    callableStatement.setDate(4, new java.sql.Date(today.getTime()));

    callableStatement.executeUpdate();
    System.out.println("Record is inserted into PERSON table!");
    callableStatement.close();
    dbConnection.close();
  }
}