connection.prepareStatement(“call R_sum_date_table_Sql(?,??”);
通过preparestatement可以调用可以返回 数据集 跟sql语句操作一摸一样
但是有个缺点就是不能输出参数 要使用输出参数就必须使用callablestatement
有进要通过jdbc调用存储过程,来说一下怎样来实现?
在我见过的有两种情况:
1)返回一个结果集(ResultSet)。
2)返回一个特定的值。
下面来详细的说明。
1)返回一个结果集(ResultSet),这种类似通常的处理结果集
如果事先就有一个类似如下的procedure
CREATE PROCEDURE getShipQuantity @jsid int AS
SELECT jf_js_id,SUM(jf_ship_quantity) AS shipqty
FROM tjobsheet_finish f WHERE (jf_js_id=@jsid)
GROUP BY jf_js_id
SELECT jf_js_id,SUM(jf_ship_quantity) AS shipqty
FROM tjobsheet_finish f WHERE (jf_js_id=@jsid)
GROUP BY jf_js_id
那么我们将通过如下的代码来调用
String sql = "{ call getShipQuantity(?) }";
Connection con = getSession().connection();//通过hibernate得到的连接
ResultSet rs = null;
BigDecimal shipQuantity = new BigDecimal(0);
try{
CallableStatement cs = con.prepareCall(sql);
cs.setInt(1,jsoId);//设置输入参数
rs = cs.executeQuery();//返回结果集
if(rs.next()){
shipQuantity = new BigDecimal(rs.getDouble(2));
}
logger.debug("shipQuantity --------------------- "+shipQuantity);
}catch(Exception e){
logger.debug(e);
}
Connection con = getSession().connection();//通过hibernate得到的连接
ResultSet rs = null;
BigDecimal shipQuantity = new BigDecimal(0);
try{
CallableStatement cs = con.prepareCall(sql);
cs.setInt(1,jsoId);//设置输入参数
rs = cs.executeQuery();//返回结果集
if(rs.next()){
shipQuantity = new BigDecimal(rs.getDouble(2));
}
logger.debug("shipQuantity --------------------- "+shipQuantity);
}catch(Exception e){
logger.debug(e);
}
2)返回一个特定的值。也就是说,在procedure的定义中已经用output输出参数了。请看下面的proceduer
create procedure getSingleWgt @@singleWgt numeric(8,3) output,@jsnum varchar(11) = '0000-0480'
as
declare @stwgt numeric(8,3)
select @stwgt = sum(b.stwgt)
from js as a
inner join jsactdtl as b
on a.jsnum = b.jsnum
where a.completion = 1
and b.stflag = 22
and a.jsnum = @jsnum
select @@singleWgt = (@stwgt/orderedqty) from js where jsnum = @jsnum
as
declare @stwgt numeric(8,3)
select @stwgt = sum(b.stwgt)
from js as a
inner join jsactdtl as b
on a.jsnum = b.jsnum
where a.completion = 1
and b.stflag = 22
and a.jsnum = @jsnum
select @@singleWgt = (@stwgt/orderedqty) from js where jsnum = @jsnum
那么我们将通过如下的代码来调用
String sql = "{ call getSingleWgt(?,?) }";
Connection con = getSession().connection();//得到connection
try{
CallableStatement cs = con.prepareCall(sql);//通过它来执行sql
cs.registerOutParameter(1,java.sql.Types.FLOAT);//注册输出参数
cs.setString(2,shipment.getJsnum());//指出输入参数
if(cs.execute()){//执行
float output = cs.getFloat(1);//返回值
}
}catch(Exception e){
logger.debug(e);
}
Connection con = getSession().connection();//得到connection
try{
CallableStatement cs = con.prepareCall(sql);//通过它来执行sql
cs.registerOutParameter(1,java.sql.Types.FLOAT);//注册输出参数
cs.setString(2,shipment.getJsnum());//指出输入参数
if(cs.execute()){//执行
float output = cs.getFloat(1);//返回值
}
}catch(Exception e){
logger.debug(e);
}