来自:http://songlia2.blog.hexun.com/13095398_d.html
今天有同志问我这个问题,据说是取不到返回参数,于是连抄带写,胡乱写了点代码测试一下,完整代码如下(有一段时间没怎么用VC,写的不好,见笑一下):
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
CoInitialize(NULL);
_ConnectionPtr pConnection = NULL;
_CommandPtr pCommand = NULL;
_RecordsetPtr pRecordset = NULL;
_ParameterPtr pParameter = NULL;
try
{
pConnection.CreateInstance(__uuidof(Connection));
pParameter.CreateInstance(__uuidof(Parameter));
pCommand.CreateInstance( __uuidof(Command));
pConnection->Open(CONNECTION_STRING,"sa","",-1);
pCommand->ActiveConnection = pConnection;
pCommand->CommandType = adCmdStoredProc;
_bstr_t storename("test");
pCommand->put_CommandText(storename);
pCommand->Parameters->Append(pCommand->CreateParameter("@value",
adVarChar, adParamInputOutput, 50, "what"));
pRecordset = pCommand->Execute(NULL, NULL, adCmdStoredProc);
while(!(pRecordset->GetadoEOF()))
{
<!-- Inject Script Filtered -->
_bstr_t strRecord = pRecordset->Fields->GetItem("record")->GetValue().bstrVal;
CString value = strRecord;
TRACE("result: %s\n", value) ;
pRecordset->MoveNext();
}
TRACE("recordcount: %d\n", pRecordset->RecordCount);
pRecordset->Close();
CString out(pCommand->Parameters->GetItem(_variant_t("@value"))->GetValue().bstrVal);
TRACE("return : %s", out);
}
catch(_com_error err)
{
TRACE("error: %s", err.Description());
pConnection->Close();
}
::CoUninitialize();
return nRetCode;
}
通过测试最终发现,执行存储过程时需调用Command对象的Execute方法,该方法返回一个RecordSet对象,但我发现这个
RecordSet对象尽管是有内容的,但是RecordCount的值是-1,不知道是为什么.在取返回参数之前,必须把这个RecordSet关闭,
否则是取不到返回参数的.
今天又上了一课了.