分享

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

 知识存储馆 2014-08-07

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

 

  1. create procedure proc_test 
  2. @q_type int,
  3. @value int,
  4. @count int output
  5. as
  6. begin
  7.      update mytable set value = @value where type = @q_type
  8.      set @count = @@rowcount
  9.      select * from mytable where type = @q_type
  10. end
  11. go

这个存储过程,既有输出参数,又有返回结果集,而用java调用他,两者都要取到,则代码如下:

 

  1. Connection conn = MyConnectionPool.getConnection();
  2. CallableStatement cstmt = conn.prepareCall("{call proc_test(?,?,?)}");
  3. cstmt.setInt(1, type);
  4. cstmt.setInt(2, value);
  5. cstmt.registerOutParameter(3, java.sql.Types.INTEGER);
  6. ResultSet rs = cstmt.executeQuery();
  7. while(rs.next()) {
  8.    doSomeThingToResultSet(rs);
  9. }
  10. doSomeThingToOutParameter(cstmt.getInt(3));
  11. rs.close();
  12. cstmt.close();
  13. conn.close();

其中的关键在于哪儿呢?

  1. 必须用cstmt.executeQuery()来取得结果集,用cstmt.execute()然后getResultSet()是取不到的,而executeQuery()能保证先执行update再select;
  2. 获得输出参数的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.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多