What is CallableStatement?

•Callable statements are a SQL statement that invokes stored procedures (database Procedure Call).
•The statement that invokes the stored procedure should use JDBC CallableStatement class.
•Callable statement is prepared by calling prepareCall() method of Connection class.
•Sysntax of prepareCall()
con.prepareCall(“{ ? = call stored_procedure_name (?, ?, ?.....)}”)
or
con.prepareCall(“{ call stored_procedure_name (?, ?, ?.....)}”)
where con is the object of Connection and ‘?’ represents parameter.
•Types of parameters are passed to callable statement such as IN,OUT, INOUT parameters.
•IN parameter contains any data that needs to be passed to the stored procedure and whose value is assigned by using setXXX(index,value) method.
•OUT parameter contains the value returned by the stored procedure,if any.The OUT patametere is registered by invoking registerOutParameter(index, type) of CallableStatement. The value of OUT parameter is obtained by xxx getXXX(index) of CallableStatement after execution of the boolean execute() method CallableStatement object.
•The INOUT is a single parameter that is used to both pass the information and retrieve the information.
Example:
import java.sql.*;
class demo
{
public static void main(String[] args){
Connection con=null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","oracle");
String query="{CALL LastOrderNumber(?)}";
CallableStatement cs=con.prepareCall(query);
cs.registerOutParameter(1,Types.VARCHAR);
cs.execute();
String orderno=cs.getString(1);
System.out.println(orderno);
cs.close();
}catch(Exception e){
System.out.println("the exception is::::->"+e);
}
finally{
try{
con.close();}
catch(Exception e){
System.out.println("2nd try block exception:::->"+e);
}}}};

Here LastOrderNumber is a stored procedure which retrives the most recently used ordernumber. It requires one parameter which is represented by question mark place holder.

No comments:

Post a Comment