首先在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("第一列的屬性名稱"))));