Wednesday, May 30, 2007

About CallableStatement Class:

A CallableStatement object provides a way to call stored procedures in a standard way for all DBMSs.
A stored procedure is stored in a database; the call to the stored procedure is what a CallableStatement object contains. This call is written in an escape syntax that may take one of two forms: one form with a result parameter, and the other without one.
A result parameter, a kind of OUT parameter, is the return value for the stored procedure. Both forms may have a variable number of parameters used for input (IN parameters), output (OUT parameters), or both (INOUT parameters). A question mark serves as a placeholder for a parameter.

The syntax for invoking a stored procedure in JDBC is shown below. Note that the square brackets indicate that what is between them is optional; they are not themselves part of the syntax.

{call procedure_name[(?, ?, ...)]}

The syntax for a procedure that returns a result parameter is:

{? = call procedure_name[(?, ?, ...)]}

The syntax for a stored procedure with no parameters would look like this:

{call procedure_name}

Example:

String command = "{? = call TestingStoredProcedure(?, ?, ?)}";
CallableStatement cstmt = conn.prepareCall (command);

// Register arg1 OUT parameter
cstmt.registerOutParameter(1, Types.INTEGER);

// Pass in value for IN parameter
cstmt.setInt(2, 4);

// Register arg3 OUT parameter
cstmt.registerOutParameter(3, Types.INTEGER);

// Execute TestingStoredProcedure
ResultSet rs = cstmt.executeQuery();

// executeQuery returns values via a resultSet
while (rs.next())
{
// get value returned by TestingStoredProcedure
boolean b = rs.getBoolean(1);
System.out.println("return value from TestingStoredProcedure= " + b);
}

// Retrieve OUT parameters from TestingStoredProcedure
int i = cstmt.getInt(1);
System.out.println("arg1 OUT parameter value = " + i);

int k = cstmt.getInt(3);
System.out.println("arg3 OUT parameter value = " + k);

No comments: