Java中执行存储过程时,有时需要将存储过程的返回值获取到,并进行一些操作;
一、涉及的Jar包如下:
import java.sql.CallableStatement;
import org.hibernate.Session;
二、主要实现逻辑如下:
Session session = null;
CallableStatement callableStatement=null;
try {
String p_group_pf_sec = "call "+wf_id+"(?,?,?,?,?)"; //?是占位符包括参数和返回值
session=HibernateUtil.getSession(“获取session”);
callableStatement= session.connection().prepareCall(p_group_pf_sec);
callableStatement.setString(1, param1); //存储过程参数
callableStatement.setString(2, param2); //存储过程参数
callableStatement.setString(3, param3); //存储过程参数
callableStatement.registerOutParameter(4, Types.INTEGER); //存储过程返回状态
callableStatement.registerOutParameter(5, Types.VARCHAR); //存储过程返回信息
callableStatement.execute();//执行存储过程
log.append(" 执行完毕!");
//存储过程执行状态
String state = callableStatement.getString(4); //获取返回状态
//存储过程错误信息
String message = callableStatement.getString(5); //获取返回信息
if("0".equals(state)){ //0 成功 1失败
isSuccess.put("result", true);
}else{
isSuccess.put("result", false);
log.append(" 执行失败! 存储过程内部异常,原因:"+message);
}
} catch (Throwable e) {
isSuccess.put("result", false);
String error=e.getLocalizedMessage();
log.append(" 执行失败! 执行存储过程异常,原因:"+error);
}finally{
//关闭连接,关闭session
if(callableStatement!= null){
try {
callableStatement.close();
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
if(session != null && session.isConnected()){
session.close();
}
}