c++ ado 调用存储过程并得到输出参数和返回值

时间:2021-03-07 21:15:56
// AccessSqlserverByAdo.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"


#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;

#import "C:\Program Files\Common Files\System\ado\msado15.dll" rename("EOF", "adoEOF") rename("BOF", "adoBOF")
using namespace ADODB;

int _tmain(int argc, _TCHAR* argv[])
{
    ::CoInitialize(NULL);   
    _ConnectionPtr m_pConnection=NULL;  
    
    m_pConnection.CreateInstance(__uuidof(Connection));  

  
      
    _bstr_t strConnect = "Provider=SQLOLEDB.1;Password=1111111;Persist Security Info=True; \
                         User ID=sa;Initial Catalog=SoftwareVerification;Data Source=112.74.105.204"; 
    

    //下面代码执行一个查询
    /*
    try
    {
        _RecordsetPtr m_pRecordset=NULL;  
     m_pRecordset.CreateInstance(__uuidof(Recordset));
        m_pConnection->Open(strConnect,"","",adModeUnknown);
        _variant_t vAffected;
        _bstr_t bstrSql("select user_name,user_password from userssss");
        m_pRecordset = m_pConnection->Execute(bstrSql,&vAffected,adCmdText);
        while(!m_pRecordset->adoBOF)
        {
            _variant_t UserName = m_pRecordset->GetCollect(_variant_t((long)0));
            _variant_t PassWord = m_pRecordset->GetCollect("user_password");
            if(UserName.vt != NULL)
            {
                cout<<(LPCSTR)(_bstr_t)UserName<<"   "<<(LPCSTR)(_bstr_t)PassWord<<endl;
            }
            m_pRecordset->MoveNext();
        }
        m_pRecordset->Close();
        m_pConnection->Close();
    }
    catch(_com_error e)
    {
        wcout<<e.Description()<<endl;
    }
    */

    //调用存储过程
        try
    {
        m_pConnection->Open(strConnect,"","",adModeUnknown);
        _CommandPtr cmmd;
        HRESULT hr = cmmd.CreateInstance(__uuidof(Command));

        cmmd->Parameters->Append(cmmd->CreateParameter(_bstr_t("Return"),adInteger,adParamReturnValue,4));
        cmmd->Parameters->Append(cmmd->CreateParameter(_bstr_t("strUserName"),adVarChar,adParamInput,50,"zds"));
        cmmd->Parameters->Append(cmmd->CreateParameter(_bstr_t("strPassWord"),adVarChar,adParamInput,50,"111"));
        cmmd->Parameters->Append(cmmd->CreateParameter(_bstr_t("nSoftWareID"),adInteger,adParamInput,4,"1"));
        cmmd->Parameters->Append(cmmd->CreateParameter(_bstr_t("strMsg"),adVarChar,adParamOutput,50));
        

        cmmd->CommandText = _bstr_t("UserLogin");
        cmmd->ActiveConnection = m_pConnection;
        cmmd->CommandType = adCmdStoredProc;
        cmmd->Execute(NULL,NULL,adCmdStoredProc);
        string strRet = (const char*)(_bstr_t)cmmd->Parameters->GetItem("strMsg")->GetValue();
        int nRet = cmmd->Parameters->GetItem("Return")->GetValue();
        cout<<strRet<<endl;
    }
    catch(_com_error e)
    {
        wcout<<e.Description()<<endl;
    }

    ::CoUninitialize();
    return 0;
}