6.3.7.5.2 Create a CallableStatement Object
To create a CallableStatement object, you need to use one of methods defined in the Connection class, prepareCall(). When the SQL92 syntax is used to create the CallableStatement object, it will look like:
CallableStatement cstmt = null;
try{
String query = “{call FacultyCourse(?,?)}”; cstmt = LogInFrame.con.prepareCall(query); . . .
The operation sequence of this piece of code to create a new CallableStatement object is:
1) A new null CallableStatement object, cstmt, is first declared.
2) A try block is used to create the query string with the SQL92 syntax. The name of the stored procedure to be called is FacultyCourse() with two arguments; the first one is an input parameter, faculty _ name, and the second one is an output parameter used to store all course _ id taught by the selected faculty. Both parameters are represented by placeholders, and they are positional parameters.
3) The CallableStatement object is created by calling the prepareCall() method, which belongs to the Connection class with the query string as the argument.
Next let’s take a look at how to set up the input parameters for this object.
6.3.7.5.3 Set the Input Parameters
All input parameters used for a CallableStatement interface must be clearly bound to the associated IN parameters in a stored procedure by using a setXXX() method. This setXXX() method can be divided into three categories based on the different data types:
1) The primitive data type method
2) The object method
3) The stream method
For the primitive and the object method, the syntax is identical, and the difference between them is the type of value that is assigned. For the stream method, both the syntax and the data types are different.
Set Primitive Data Type and Object IN Values
The primitive data type means all built-in data types used in the Java programming language. The syntax of setting a primitive data type or an object value method is,
setXXX(int position, data _ type value);
where XXX means the associated value type to be assigned, position is an integer used to indicate the relative position of the IN parameter in the query statement or the stored procedure and value is the actual data value to be assigned to the IN parameter.
Some popular setXXX() methods are:
setBoolean(), setByte(), setInt(), setDouble(), setFloat(), setLong(), setShort(), setString(),
setObject(), setDate(), setTime(), setTimeStamp()
An example of using the setXXX() method is:
String query = “SELECT product, order _ date FROM Order “+ “WHERE order _ id =? AND customer =?”; PreparedStatement pstmt = con.prepareStatement(query); setInt(1, 101);
setString(2, “Tom Johnson”);