1. 程式人生 > >C++連線access資料庫

C++連線access資料庫

使用C++程式語言,連線對Access資料庫進行操作,常用的方法有DAO和ADO兩種方式,本文將介紹採用ADO的方式方位Access資料庫。

       先介紹一下ADO,ADO (ActiveX Data Objects) 是一個用於存取資料來源的COM組建。它提供了程式語言和統一資料訪問方式OLE DB的一箇中間層。允許開發人員編寫訪問資料的程式碼而不用關心資料庫是如何實現的,而只用關心到資料庫的連線。

       在程式的開始,首先匯入所需要的庫:#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename
("EOF", "adoEOF") ,這裡重新命名EOF是必要的,因為典型的VC應用都已經定義了EOF作為常數-1。 完整的程式如下,以註釋的形式來對程式進行解釋: _ConnectionPtr m_pConnection; //連線access資料庫的連結物件 _RecordsetPtr m_pRecordset; //結果集物件 CoInitialize(NULL); //初始化 m_pConnection.CreateInstance(__uuidof(Connection)); //例項化物件 //連到具體某個mdb ,此處的的Provider語句因Access版本的不同而有所不同。
try { m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MyAccess.mdb","","", adModeUnknown); } catch(_com_error e) { AfxMessagebox(_T("資料庫連線失敗!")); return; } m_pRecordset.CreateInstance
(__uuidof(Recordset)); //例項化結果集物件 //執行sql語句 try { CString sql= _T("select * from Patient"); m_pRecordset->Open(sql, m_pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText); } catch(_com_error *e) { AfxMessageBox(e->ErrorMessage()); if(m_pConnection->State) { m_pConnection->Close(); m_pConnection= NULL; } return ; } //處理結果集 try { //若結果為空,結束 if(m_pRecordset->BOF) { AfxMessageBox_T(("表內資料為空!")); if(m_pConnection->State) { m_pRecordset->Close(); m_pRecordset = NULL; m_pConnection->Close(); m_pConnection= NULL; } return ; } //遊標定位到第一條記錄 m_pRecordset->MoveFirst(); _variant_t var; //從結果集中取出的資料放到var中 char *name; while(!m_pRecordset->adoEOF) { var= m_pRecordset->GetCollect("Name"); //要取欄位的名稱。 if(var.vt != VT_NULL) { name= _com_util::ConvertBSTRToString((_bstr_t)var); //轉換成char*型別 } string MyName = name; m_pRecordset->MoveNext(); } } catch(_com_error *e) { AfxMessageBox(e->ErrorMssage()); } //退出程式時的處理 ,關閉資料庫的相關操作 if(m_pConnection->State) { m_pRecordset->Close(); m_pRecordset = NULL; m_pConnection->Close(); m_pConnection= NULL; }