Java调用SQL Server存储过程同时返回参数和结果集

转自:http://blog.csdn.net/kirbylynx/archive/2008/12/09/3483449.aspx

 

比如SQL Server的一个存储过程:

 

create procedure proc_test 
@q_type int,
@value int,
@count int output
as
begin
     update mytable set value = @value where type = @q_type
     set @count = @@rowcount
     select * from mytable where type = @q_type
end
go
这个存储过程,既有输出参数,又有返回结果集,而用java调用他,两者都要取到,则代码如下:

 

Connection conn = MyConnectionPool.getConnection();
CallableStatement cstmt = conn.prepareCall("{call proc_test(?,?,?)}");
cstmt.setInt(1, type);
cstmt.setInt(2, value);
cstmt.registerOutParameter(3, java.sql.Types.INTEGER);
ResultSet rs = cstmt.executeQuery();
while(rs.next()) {
   doSomeThingToResultSet(rs);
}
doSomeThingToOutParameter(cstmt.getInt(3));
rs.close();
cstmt.close();
conn.close();
其中的关键在于哪儿呢?

必须用cstmt.executeQuery()来取得结果集,用cstmt.execute()然后getResultSet()是取不到的,而executeQuery()能保证先执行update再select;
获得输出参数的cstmt.getInt(3)必须在处理完结果集的所有内容后再执行,如果把上述代码改成如下:
........
doSomeThingToOutParameter(cstmt.getInt(3));
while(rs.next()) {
   doSomeThingToResultSet(rs);
}
........

       后果就是,在rs.next()的时候,会抛出异常:java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Object has been closed.

很有趣,不是么?


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/kirbylynx/archive/2008/12/09/3483449.aspx

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值