关于存储过程的ADO调用的一些心得(输出参数,返回值)

在一个项目中,我需要用到存储过程来访问数据,为了提供一个比较一致的接口以便调用,我没有使用CreateParameter(),而是调用CommandPtr的Refresh()函数先从数据库中查询参数.
_ConnectionPtr m_pConn;
m_pConn.CreateInstance(__uuidof(Connection));
m_pConn->Open("driver={SQL Server};server=127.0.0.1;DATABASE=pub;UID=sa;PWD=", "","",0);

_CommandPtr m_pCommand;
m_pCommand.CreateInstance(__uuidof(Command));
_RecordsetPtr m_pRecordset;
m_pRecordset.CreateInstance(__uuidof(Recordset));

m_pCommand->ActiveConnection = m_pConn;
m_pCommand->CommandText = "SP_XX";//存储过程名
m_pCommand->PutCommandType(adCmdStoredProc);
m_pCommand->Parameters->Refresh();//从数据库查询参数信息

> 接下来就可以对每一个参数赋值了:
> long cnt = m_pCommand->Parameters->GetCount();//取得参数的个数
> for(long k=1;k

 1<cnt;k++)>  {//由于ADO中认为返回值是第一个参数,因此这里用k=1滤掉第一个参数   
 2&gt;  m_pCommand-&gt;Parameters-&gt;GetItem(k)-&gt;Value = XXX;//按存储过程的参数顺序给参数赋值   
 3&gt;  }   
 4&gt; 
 5
 6现在可以执行这个存储过程了   
 7m_pRecordset = m_pCommand-&gt;Execute(0,0,adCmdStoredProc);   
 8这个时候,如果接下来用   
 9_variant_t ret_val = m_pCommand-&gt;Parameters-&gt;GetItem((long)0)-&gt;Value;   
10那么将得不到值   
11而如果像下面这样调用的话就可以得到返回值了   
12m_pRecordset-&gt;Close();   
13_variant_t output_para = m_pCommand-&gt;Parameters-&gt;GetItem((long)0)-&gt;Value;   
14MS ADO.net给这一现象的回复是:   
15You can think of a stored procedure as a function in your code. The function doesn’t return a value until it has executed all of its code. If the stored procedure returns results and you haven’t finished processing these results, the stored procedure hasn’t really finished executing. Until you’ve closed the  DataReader  , the return and output parameters of your  Command  won’t contain the values returned by your stored procedure.   
16也就是说Execute()函数应该看成是直到m_pRecordset关掉以后才会正确返回.   
17  
18关于输出参数的处理也和这一样,因为返回值本身就是当成输出参数来处理的.   
19通过这种方法,我们可以得到一个存储过程的返回值和结果集,而且对于所有的存储过程都可以一样使用,不必为某个特定的存储过程去写代码,具有一定的通用性.</cnt;k++)>
Published At
Categories with 数据库类
comments powered by Disqus