Java CallableStatement registerOutParameter, what does it do?

neilnm picture neilnm · Mar 11, 2014 · Viewed 23.6k times · Source

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;

Answer

anttix picture anttix · Mar 11, 2014

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