MFC通過ADO串連Oracle資料庫

來源:互聯網
上載者:User

首先在StdAfx.h標頭檔中加入#import "c:\program files\common files\system\ado\msado15.dll"\

no_namespace rename("EOF","adoEOF")

然後在App類的標頭檔中聲名

public:  _ConnectionPtr m_pConnection;//連線物件指標

接著在App類的InitInstance()函數中加入下列代碼:

 AfxOleInit();//初始化COM

 try//串連資料庫

 {

  m_pConnection.CreateInstance(__uuidof(Connection));

  _bstr_t strConnect="Provider=MSDAORA.1;User ID='system';Password='renzh';Data Source=orcl;Persist Security Info=False;";

  m_pConnection->Open(strConnect,"system","renzh",adModeUnknown);

 }

 catch(_com_error e)

 {

  AfxMessageBox(TEXT("資料庫連接出錯!"));

  AfxMessageBox(e.Description());

 }

在App類響應EXITINSTANCE的訊息中也可以加上:

if (m_pConnection->State)

 m_pConnection->Close();

m_pConnection->Release();

我認為也沒有這一步的必要(我自己是沒有加的)

 

然後資料庫就開啟了,在所有的類中都可以這樣調用:theApp. m_pConnection->Execute((_bstr_t)sql,NULL,adCmdText);

然後在要訪問記錄集的地方聲名一個記錄集指標:

CString sql=_T("這裡面是執行語句!!"):

_RecordsetPtr pRs("ADODB.RecordSet");

 pRs->Open((_bstr_t)sql,_variant_t((IDispatch *)theApp.m_pConnection,true),adOpenStatic,adLockOptimistic,adCmdText);

if (!(pRs->adoBOF))//如果記錄集不空

{

……

}

取出記錄集資訊可以用pRs-> GetCollect_r(_T("某個屬性列名")));它的傳回值是_variant_t,根據需要可以對它進行轉換。如在ClistCtrl對象的插入中:

m_grd.SetItemText(0,0,(LPTSTR)(_bstr_t)(pRs-> GetCollect_r(_T("第一列的屬性名稱"))));

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.