c++调用ado执行带参数的sql(非存储过程)

本文介绍如何使用C++和ADO进行参数化的SQL更新操作,详细解释了使用问号作为参数占位符的方法,以及如何正确地创建并附加参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

///
//      PrintProviderError Function          //
///

void PrintProviderError(_ConnectionPtr pConnection)
{
    // Print Provider Errors from Connection object.
    // pErr is a record object in the Connection's Error collection.
    ErrorPtr  pErr = NULL;

    if( (pConnection->Errors->Count) > 0)
    {
        long nCount = pConnection->Errors->Count;
        // Collection ranges from 0 to nCount -1.
        for(long i = 0; i < nCount; i++)
        {
            pErr = pConnection->Errors->GetItem(i);
            TRACE(_T("\tError number: %x\t%s"), pErr->Number,
                (LPCTSTR)pErr->Description);
        }
    }
}

//
//      PrintComError Function      //
//

void PrintComError(_com_error &e)
{
    _bstr_t bstrSource(e.Source());
    _bstr_t bstrDescription(e.Description());

    // Print Com errors.
    TRACE(_T("Error\n"));
    TRACE(_T("\tCode = %08lx\n"), e.Error());
    TRACE(_T("\tErrorMessage = %s\n"), (LPCTSTR)e.ErrorMessage());
    TRACE(_T("\tSource = %s\n"), (LPCTSTR) bstrSource);
    TRACE(_T("\tDescription = %s\n"), (LPCTSTR) bstrDescription);
}

///
//      ExecuteSQL Function          //
///
void ExecuteSQL()
{
    CoInitialize(NULL);
    HRESULT    hr = S_OK;

    // Define string variables.      
    _bstr_t strCnn("Provider=SQLOLEDB.1;Password=;Persist Security Info=True;User ID=sa;Initial Catalog=Participants;Data Source=(local)");

    // Define ADO object pointers.
    // Initialize pointers on define.
    _ConnectionPtr  pConnection = NULL;
    _CommandPtr     pCmd  = NULL;
    _RecordsetPtr   pRst  = NULL;
    _ParameterPtr   pParam = NULL;

    try
    {
        // Open connection.
        pConnection.CreateInstance(__uuidof(Connection));
        pConnection->Open (strCnn, "", "", adConnectUnspecified);

        // Please note that question mark, a question mark represents a parameter
        _bstr_t strSQL("update p1 set phonenumber='3344' where id=?;");

        // Create command object.
        pCmd.CreateInstance(__uuidof(Command));
        pCmd->ActiveConnection = pConnection;        
        pCmd->CommandText = strSQL;
        pCmd->CommandType = adCmdText;

        // Append some parameters
        // According to statements to maintain the order and type parameters.
        // In this case, the parameter names can be customized.
        pCmd->Parameters->Append(pCmd->CreateParameter(_T("@id"),adVarChar, adParamInput,(long)10, _T("ID002")));

        _variant_t vRecordAffected;
        vRecordAffected.vt = VT_I4;
        vRecordAffected.lVal = 0L; 

        pCmd->Execute(vRecordAffected.GetAddress(),NULL,adCmdText); 


        TRACE(_T("nRecordAffected=%d\r\n"),  vRecordAffected.lVal);

        // Clean up objects before exit.
        
        pCmd.Release();

        if (pRst)
        {
            if (pRst->State == adStateOpen)
                pRst->Close();
            pRst.Release();
        }

        if (pConnection)
        {
            if (pConnection->State == adStateOpen)
                pConnection->Close();
            pConnection.Release();
        }
    }
    catch (_com_error &e)
    {
        PrintProviderError(pConnection);
        PrintComError(e);
    }
    ::CoUninitialize();
}

c#我们知道sql语句中的参数,用“@param”来代替

但是在c++中,用“?”问号代替

_bstr_t strSQL("update p1 set phonenumber='3344' where id=?;")中,参数用?号来代替

再创建参数

  pCmd->CreateParameter(_T("@id"),adVarChar, adParamInput,(long)10, _T("ID002"))

其中“@id”只起到可读性作用,并不会根据此标识,自动绑定到sql相应位置,

也就是说,参数的添加

pCmd->Parameters->Append,要按sql中参数的顺序来添加,否则会乱了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值