Question

I'm following a guide regarding callable statements.

In this guide, it says that I need to register the out parameter with the follow statement:

callsts.registerOutParameter(2, java.sql.Types.VARCHAR);

QUESTION: Why do I need to do this/what does it do ?

Complete Java code:

String getcall = "{call gettitle (?,?)}";
CallableStatement callsts = connect.prepareCall(getcall);
int nID = 15;
callsts.setInt(1, nID);
callsts.registerOutParameter(2, java.sql.Types.VARCHAR);
callsts.execute();
String calltitle = callsts.getString(2);
System.out.println("Callable Stamement Title: "+calltitle);       

mySQL procedure:

DELIMITER $$ 
DROP PROCEDURE IF EXISTS `nothingtowear`.`gettitle` $$
CREATE PROCEDURE  `nothingtowear`.`gettitle` (
IN nothingtowear_ID INT,
OUT nothingtowear_TITLE VARCHAR( 255 )) 
BEGIN 
SELECT Title INTO nothingtowear_TITLE
FROM articles
WHERE ID = nothingtowear_ID;
END $$
DELIMITER;
Was it helpful?

Solution

Out parameters are parameters passed to a SQL stored procedure that the procedure writes to. In MySQL it can also be done via a SET command

SET out_param1 = value

See mysql stored-procedure: out parameter for another example

registerOutParameter will tell JDBC driver that it this is an otuput parameter and needs to be treated as such. E.g. it needs to use special syntax to call the procedure and retrieve output values after a statement is called

OTHER TIPS

registerOutParameter is used to create a variable i.e. sql types on database server, so which is used to store value, and can get access using index in java calling stored procedures and functions context.

for example:

callableStatement.registerOutParameter(1, java.sql.Types.VARCHAR);
......
// get cursor and cast it to ResultSet
String var = callableStatement.getString(1);

In Oracle:

callableStatement.registerOutParameter(1, OracleTypes.CURSOR);
// get cursor and cast it to ResultSet
ResultSet rs = (ResultSet) callableStatement.getObject(1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top