天天看點

mfc使用ado連接配接資料庫1.設定資料源2.建立包含資料庫的MFC對話框(其它也可以)工程,建立ADOConn類3.編寫代碼連接配接資料庫(這裡我用的是ACCESS資料庫)

1.設定資料源

打開控制台--->系統和安全--->管理工具--->ODBC Data Sources(32 bit)

這裡需要注意的是,vc6.0是32位的,是以這裡的資料源也必須是32位的,否則是連接配接不上的,

這裡我使用的是ACCESS資料庫,資料源的配置如下:

mfc使用ado連接配接資料庫1.設定資料源2.建立包含資料庫的MFC對話框(其它也可以)工程,建立ADOConn類3.編寫代碼連接配接資料庫(這裡我用的是ACCESS資料庫)

2.建立包含資料庫的MFC對話框(其它也可以)工程,建立ADOConn類

在工程中我們需要建立一個普通類ADOConn

mfc使用ado連接配接資料庫1.設定資料源2.建立包含資料庫的MFC對話框(其它也可以)工程,建立ADOConn類3.編寫代碼連接配接資料庫(這裡我用的是ACCESS資料庫)

然後在ADOConn類頭檔案中加入以下導入聲明和變量、函數聲明:

ADOConn.h---------------------------------------------------------------------------------

#import "c:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")//引入ADO庫檔案

public:

    _ConnectionPtr m_pConnection;//連接配接對象指針

    _RecordsetPtr m_pRecordset;//記錄集對象指針

    _CommandPtr m_pCommand;//指令對象指針

    ADOConn();

    virtual ~ADOConn();

    BOOL OnInitADOConn(CString Connstr);//初始化連接配接資料庫

    BOOL ExecuteSQL(CString strSQL);//執行SQL語句

    BOOL ExecuteProc(CString ProcName);//執行存儲過程

    BOOL GetCollect(CString FieldName,CString & strDest);//獲得某個字段的值

    BOOL GetRecordSet(CString strSQL);//獲得記錄集

    int GetRecordCount();//獲得記錄數

     //判斷表TableName中是否存在字段KeyName的值為KeyValue的記錄

    BOOL RecordExist(CString TableName,CString KeyName,CString KeyValue);

    BOOL MoveFirst();//移動到第一條記錄

    BOOL MoveNext();//移動到下一條記錄

    BOOL Close();//關閉記錄集

    BOOL CloseADOConnection();//關閉連接配接

    void dump_com_error(_com_error &e);//錯誤詳細資訊

ADOConn.h---------------------------------------------------------------------------------

然後在ADOConn類源檔案中加入函數實作:

ADOConn.cpp---------------------------------------------------------------------------------

ADOConn::ADOConn()//構造函數

{

}

ADOConn::~ADOConn()//析構函數

{

}

BOOL ADOConn::OnInitADOConn(CString ConnStr)//初始化連接配接資料庫

{

    try{

        m_pRecordset.CreateInstance("ADODB.Recordest");

        m_pCommand.CreateInstance("ADODB.Command");

        m_pConnection.CreateInstance("ADODB.Connection");

        _bstr_t strConnect=(_bstr_t)ConnStr;

        m_pConnection->Open((_bstr_t)strConnect,"","",adModeUnknown);

        AfxMessageBox("資料庫連接配接成功");

        return true;

    }catch(_com_error e){

        AfxMessageBox("資料庫連接配接失敗");

        return false;

    }

}

BOOL ADOConn::ExecuteSQL(CString strSQL)//執行SQL語句

{

    try{

        m_pConnection->BeginTrans();

        m_pConnection->Execute(_bstr_t(strSQL),NULL,adCmdText);

        m_pConnection->CommitTrans();

        return true;    

    }catch(_com_error e)

    {

        m_pConnection->RollbackTrans();

        AfxMessageBox("執行SQL語句失敗");

        return false;

    }

}

BOOL ADOConn::ExecuteProc(CString ProcName)//執行存儲過程

{

    try{

        m_pCommand->ActiveConnection=m_pConnection;

        m_pCommand->CommandText=_bstr_t(ProcName);

        m_pCommand->Execute(NULL,NULL,adCmdStoredProc);

        return true;

    }catch(_com_error e){

        AfxMessageBox("執行存儲過程失敗");

        return false;

    }

}

BOOL ADOConn::GetCollect(CString FieldName,CString & strDest)//獲得某個字段的值

{

    VARIANT vt;

    try{

        vt=m_pRecordset->GetCollect(_variant_t(FieldName));

        switch(vt.vt){

        case VT_BSTR:

                    strDest=(LPCSTR)_bstr_t(vt);

                    break;

        case VT_DECIMAL:

                    strDest.Format("%d",vt.intVal);

                    break;

        case VT_DATE:

            {

                DATE dt=vt.date;

                COleDateTime da=COleDateTime(dt);

                strDest.Format("%d-%d-%d %d: %d: %d",da.GetYear(),da.GetMonth(),da.GetDay(),da.GetHour(),da.GetMinute(),da.GetSecond());

                break;

            }

        case VT_NULL:

                    strDest="";

                    break;

        }

        return true;

    }catch(_com_error e){

        AfxMessageBox(e.ErrorMessage());

        return false;

    }

    return true;

}

BOOL ADOConn::GetRecordSet(CString strSQL)//獲得記錄集

{

    try{

        m_pCommand->CommandText=(_bstr_t)strSQL;

        m_pCommand->ActiveConnection=m_pConnection;

        m_pCommand->CommandType=adCmdText;

        m_pRecordset=m_pCommand->Execute(NULL,NULL,adCmdText);

        return true;

    }catch(_com_error e)

    {

        AfxMessageBox("執行select語句失敗");

        return false;

    }

}

int ADOConn::GetRecordCount()//獲得記錄數

{

    DWORD nRows = 0;

    nRows=m_pRecordset->GetRecordCount();

    if(nRows==-1)

    {

        nRows=0;

        if(m_pRecordset->adoEOF!=VARIANT_TRUE) m_pRecordset->MoveFirst();

        while(m_pRecordset->adoEOF!=VARIANT_TRUE)

        {

            nRows++;

            m_pRecordset->MoveNext();

        }

        if(nRows>0)m_pRecordset->MoveFirst();

    }

    return nRows;

}

//判斷表TableName中是否存在字段KeyName的值為KeyValue的記錄

BOOL ADOConn::RecordExist(CString TableName,CString KeyName,CString KeyValue)

{

    CString countstr;

    countstr="select * from "+TableName+"where"+KeyName+"=\'"+KeyValue+"\'";

    BOOL ret =GetRecordSet(countstr);

    if(ret)

    {

        int ret2=GetRecordCount();

        if(ret2) return true;

        else return false;

    }

    else return false;

}

BOOL ADOConn::MoveFirst()//移動到第一條記錄

{

    try{

        m_pRecordset->MoveFirst();

        return true;

    }catch(_com_error e){

        AfxMessageBox("結果集移到第一個失敗");

        return false;

    }

}

BOOL ADOConn::MoveNext()//移動到下一條記錄

{

    try{

        m_pRecordset->MoveNext();

        return true;

    }catch(_com_error e){

        AfxMessageBox("結果集移到下一個失敗");

        return false;

    }

}

BOOL ADOConn::Close()//關閉記錄集

{

    try{

        m_pRecordset->Close();

        return true;

    }catch(_com_error e){

        AfxMessageBox("關系結果集失敗");

        return false;

    }

}

BOOL ADOConn::CloseADOConnection()//關閉連接配接

{

    try{

        if(m_pConnection->State)

        {

            m_pConnection->Close();

            m_pConnection=NULL;

            return true;

        }

        else{

            AfxMessageBox("關閉資料庫失敗");

            return false;

        }

    }catch(_com_error e){

        AfxMessageBox("關閉資料庫失敗");

        return false;

    }

}

void ADOConn::dump_com_error(_com_error &e)  //錯誤詳細資訊

{  

    CString ErrorStr;  

    _bstr_t bstrSource(e.Source());  

    _bstr_t bstrDescription(e.Description());  

    ErrorStr.Format( "/n/tADO Error/n/tCode = %08lx/n/tCode meaning = %s/n/tSource = %s/n/tDescription = %s/n/n",  

        e.Error(), e.ErrorMessage(), (LPCTSTR)bstrSource, (LPCTSTR)bstrDescription );  

    //在調試視窗中列印錯誤資訊,在Release版中可用DBGView檢視錯誤資訊   

    ::OutputDebugString((LPCTSTR)ErrorStr);  

#ifdef _DEBUG   

    AfxMessageBox(ErrorStr, MB_OK | MB_ICONERROR);  

#endif     

ADOConn.cpp---------------------------------------------------------------------------------

3.編寫代碼連接配接資料庫(這裡我用的是ACCESS資料庫)

這裡我們可以在任意.CPP(源檔案)中聲明ADOConn ado;

然後在其他.CPP中使用的時候,隻需要在頭部加上extern ADOConn ado;

當然,在定義的類中同樣可以使用,舉例如下:

mfc使用ado連接配接資料庫1.設定資料源2.建立包含資料庫的MFC對話框(其它也可以)工程,建立ADOConn類3.編寫代碼連接配接資料庫(這裡我用的是ACCESS資料庫)
mfc使用ado連接配接資料庫1.設定資料源2.建立包含資料庫的MFC對話框(其它也可以)工程,建立ADOConn類3.編寫代碼連接配接資料庫(這裡我用的是ACCESS資料庫)

然後進行連接配接資料庫的代碼如下:

//進行資料庫連接配接

if(!AfxOleInit())

 {

        AfxMessageBox("OLE initialzation failed");

        return FALSE;

}

CString str="DSN=rapidquery";//這個字元串中的rapidquery就是我們之前設定的資料源的名稱

ado.OnInitADOConn(str);//調用dao對象去連接配接資料庫,連接配接成功會提示,連接配接失敗也會提示。

這是連接配接成功的提示

mfc使用ado連接配接資料庫1.設定資料源2.建立包含資料庫的MFC對話框(其它也可以)工程,建立ADOConn類3.編寫代碼連接配接資料庫(這裡我用的是ACCESS資料庫)

下面的是我們access資料庫中的資訊

mfc使用ado連接配接資料庫1.設定資料源2.建立包含資料庫的MFC對話框(其它也可以)工程,建立ADOConn類3.編寫代碼連接配接資料庫(這裡我用的是ACCESS資料庫)

這是我們程式從資料庫中讀出的資訊

mfc使用ado連接配接資料庫1.設定資料源2.建立包含資料庫的MFC對話框(其它也可以)工程,建立ADOConn類3.編寫代碼連接配接資料庫(這裡我用的是ACCESS資料庫)