提个很菜的问题
网上找到的关于连接SQL SERVER的代码
void smsLogon::InitSQLServer(CString server, CString db, CString UserName, CString Pwd)
{
m_pConnection.CreateInstance("ADODB.Connection");
CString strCn;
strCn.Empty();
strCn="provider=SQLOLEDB;data source="+server
   +";initial catalog="+db
   +";userID="+UserName
   +";Password="+Pwd;
_variant_t bcnstr=_variant_t(strCn);
_variant_t bunstr=_variant_t(UserName);
_variant_t bpwdstr=_variant_t(Pwd);
//打开一个连接
try
{
  m_pConnection->Open(_bstr_t(bcnstr),_bstr_t(bunstr),
   _bstr_t(bpwdstr),-1);//adOpenUnspecified
}
catch(_com_error e)
{
  CString errormessage;
  errormessage.Format("Warning: 连接数据库发生异常. 错误信息: %s; 文件: %s; 行: %d\n", e.ErrorMessage(), __FILE__, __LINE__);
  AfxMessageBox(errormessage);
}
catch(...)
{
  AfxMessageBox("Warning :连接数据库时发生未知错误");
}
}void smsLogon::ExitDB()     //退出时关闭数据库连接
{
if(m_pConnection!=NULL)
{
  m_pConnection->Close();//关闭连接
  m_pConnection.Release();//释放对象
}
}修改为自己的数据库时应该修改哪个地方
还有编译的时候出现的2个错误 应该怎样解决
error C2039: 'Close' : is not a member of 'CsnmpagentDlg'
error C2228: left of '.Release' must have class/struct/union 如果还有更简单的方法  希望各位大大不惜赐教 
能说详细点更好 本人很菜 太简单的看不明白
本人的数据库属性是Data Source=LENOVO-306B86EC\SQLEXPRESS;Initial Catalog=qq;Integrated Security=True;Pooling=False  没有密码先谢谢各位大大了

解决方案 »

  1.   

    你的这个m_pConnection定义在哪里?是在CsnmpagentDlg里面吗?下面这是微软的一段例程
    #include <ole2.h>
    #include <stdio.h>#import "c:\Program Files\Common Files\System\ADO\msado15.dll"     no_namespace rename("EOF", "EndOfFile")// Function declarations
    inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
    void ExecuteX(void);
    void ExecuteCommand(_CommandPtr pCmdTemp, _RecordsetPtr pRstTemp);
    void PrintOutput(_RecordsetPtr pRstTemp);
    void PrintProviderError(_ConnectionPtr pConnection);
    void PrintComError(_com_error &e);////////////////////////////////
    //      Main Function         //
    ////////////////////////////////void main()
    {
        if(FAILED(::CoInitialize(NULL)))
            return;    ExecuteX();    ::CoUninitialize();
    }///////////////////////////////////
    //      ExecuteX Function        //
    ///////////////////////////////////void ExecuteX(void) 
    {
       HRESULT    hr = S_OK;    // Define string variables.
       _bstr_t strSQLChange("UPDATE Titles SET Type = "
                "'self_help' WHERE Type = 'psychology'");
       _bstr_t strSQLRestore("UPDATE Titles SET Type = "
                "'psychology' WHERE Type = 'self_help'");
       _bstr_t strCnn("Provider=sqloledb.1;Data Source=(local);"
                "Initial Catalog=Pubs;User Id=sa;Password=dzs;");    // Define ADO object pointers.
        // Initialize pointers on define.
        // These are in the ADODB::  namespace.
        _ConnectionPtr  pConnection = NULL;
        _CommandPtr     pCmdChange  = NULL;
        _RecordsetPtr   pRstTitles  = NULL;    try
        {
            // Open connection.
            TESTHR(pConnection.CreateInstance(__uuidof(Connection)));
            pConnection->Open (strCnn, "", "", adConnectUnspecified);        // Create command object.
            TESTHR(pCmdChange.CreateInstance(__uuidof(Command)));
            pCmdChange->ActiveConnection = pConnection;
            pCmdChange->CommandText = strSQLChange;        // Open Titles table, casting Connection pointer to an 
            // IDispatch type so converted to correct type of variant.
            TESTHR(pRstTitles.CreateInstance(__uuidof(Recordset)));
            pRstTitles->Open ("Titles", _variant_t((IDispatch *) pConnection, 
                true), adOpenStatic, adLockOptimistic, adCmdTable);        // Print report of original data.
            printf(
                "\n\nData in Titles table before executing the query: \n");        // Call function to print loop recordset contents.
            PrintOutput(pRstTitles);        // Clear extraneous errors from the Errors collection.
            pConnection->Errors->Clear();        // Call ExecuteCommand subroutine to execute pCmdChange command.
            ExecuteCommand(pCmdChange, pRstTitles);        // Print report of new data.
            printf(
                "\n\n\tData in Titles table after executing the query: \n");
            PrintOutput(pRstTitles);        // Use the Connection object's Execute method to
            // execute SQL statement to restore data.
            pConnection->Execute(strSQLRestore, NULL, adExecuteNoRecords);        // Retrieve the current data by requerying the recordset.
            pRstTitles->Requery(adCmdUnknown);        // Print report of restored data.
            printf(
                "\n\n\tData after exec. query to restore original info: \n");
            PrintOutput(pRstTitles);        // Clean up objects before exit.
            pRstTitles->Close();
            pConnection->Close();
        }    catch (_com_error &e)
        {
            PrintProviderError(pConnection);
            PrintComError(e);
        }
    }//////////////////////////////////////////
    //      ExecuteCommand Function         //
    //////////////////////////////////////////void ExecuteCommand(_CommandPtr pCmdTemp, _RecordsetPtr pRstTemp)
    {
        try
        {
            // CommandText property already set before function was called.
            pCmdTemp->Execute(NULL, NULL, adCmdText);        // Retrieve the current data by requerying the Recordset.
            pRstTemp->Requery(adCmdUnknown);
        }    catch(_com_error &e)
        {
            // Notify user of any errors that result from
            // executing the query.
            // Pass a connection pointer accessed from the Recordset.
            PrintProviderError(pRstTemp->GetActiveConnection());
            PrintComError(e);
        }
    }/////////////////////////////////////
    //      PrintOutput Function       //
    /////////////////////////////////////void PrintOutput(_RecordsetPtr pRstTemp)
    {
        // Ensure at top of Recordset.
        pRstTemp->MoveFirst();    // If EOF is true, then no data and skip print loop.
        if( pRstTemp->EndOfFile )
        {
            printf("\tRecordset empty\n");
        }
        else
        {
            // Define temporary strings for output conversions.
            // Initialize to first record's values.
            _bstr_t bstrTitle;
            _bstr_t bstrType;        // Enumerate Recordset and print from each.
            while(!(pRstTemp->EndOfFile))
                {
                // Convert variant string to convertable string type.
                bstrTitle = pRstTemp->Fields->GetItem("Title")->Value;
                bstrType  = pRstTemp->Fields->GetItem("Type")->Value;
                printf("\t%s, %s \n", 
                    (LPCSTR) bstrTitle,
                    (LPCSTR) bstrType);
        
                pRstTemp->MoveNext();
            }
        }
    }///////////////////////////////////////////////
    //      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);
                // pErr = pConnection->Errors->GetItem(i);
                printf("\t Error number: %x\t%s", pErr->Number,
                    pErr->Description);
            }
        }
    }//////////////////////////////////////
    //      PrintComError Function      //
    //////////////////////////////////////void PrintComError(_com_error &e)
    {
        _bstr_t bstrSource(e.Source());
        _bstr_t bstrDescription(e.Description());
        
        // Print Com errors.
        printf("Error\n");
        printf("\tCode = %08lx\n", e.Error());
        printf("\tCode meaning = %s\n", e.ErrorMessage());
        printf("\tSource = %s\n", (LPCSTR) bstrSource);
        printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
    }
      

  2.   

    你把你的Data Source=LENOVO-306B86EC\SQLEXPRESS;Initial Catalog=qq;Integrated Security=True;Pooling=False  没有密码 
    这串东西改写到下面的代码中就可以了:
    strCn="provider=SQLOLEDB;data source="+server 
       +";initial catalog="+db 
       +";userID="+UserName 
       +";Password="+Pwd; 
    _variant_t bcnstr=_variant_t(strCn); 
    _variant_t bunstr=_variant_t(UserName); 
    _variant_t bpwdstr=_variant_t(Pwd);