MFCはadoを使用してデータベースをリンクし、データベース操作


まずStdAfx.cppに追加
_ConnectionPtr m_pConnection;
_CommandPtr m_pCommand;
_RecordsetPtr m_pRecordset;

そしてStdAfx.hの#endifの下に追加
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
extern _ConnectionPtr m_pConnection;
extern _CommandPtr m_pCommand;
extern _RecordsetPtr m_pRecordset;

次にC…APPのInitlnsrance()関数に追加
//   COM,  ADO     
    AfxOleInit();
    m_pConnection.CreateInstance(__uuidof(Connection));
    // ADO           try...catch()       ,
    //                  
    try                 
    {
    //    Sql Server 
        m_pConnection->Open("driver={SQL Server};Server=....           ......;Database=..        ...;Trusted_Connection=SSPI","","",adModeUnknown);
    //Server          ,  XP-201203132217\\SQLSERVER2005     ,        [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server          
    //Database      

    }
    catch(_com_error e)
    {
    AfxMessageBox("       !");
    } 

そして必要な場所でクエリーを行います
//  ADO           try...catch()       ,
    //                   
    m_pRecordset.CreateInstance(__uuidof(Recordset));
    try
    {
    m_pRecordset->Open("SELECT * FROM ...       ...", //   s      
    m_pConnection.GetInterfacePtr(),  //       IDispatch  
    adOpenDynamic,
    adLockOptimistic,
    adCmdText);
    }
    catch(_com_error *e)
    {
    AfxMessageBox(e->ErrorMessage());
    }

    //      
    int n=0;
    _variant_t var;
    CString s;  

    while(!m_pRecordset->adoEOF)
    {
        var = m_pRecordset->GetCollect("...       ...");    
        s.Format("%s",(LPCTSTR)_bstr_t(var));
        s.Replace(' ',NULL);


        m_pRecordset->PutCollect("...       ...",_variant_t(...     ...));//  
        m_pRecordset->Update();//  

        m_pRecordset->Delete(adAffectCurrent);//     
        m_pRecordset->Update();//  

        m_pRecordset->MoveNext();//   
        n++;

    }

    m_pRecordset->Close();//