1.#import "c:/program files/common files/system/ado/msado15.dll" no_namespace rename("EOF","adoEOF")
2.初始化COM环境
BOOL CADOTest1App::InitInstance()
{
AfxEnableControlContainer();
AfxOleInit();///初始化COM库
连接数据库//
HRESULT hr;
try
{
hr = m_pConnection.CreateInstance("ADODB.Connection");///创建Connection对象
if(SUCCEEDED(hr))
{
hr = m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb","","",adModeUnknown);///连接数据库
///上面一句中连接字串中的Provider是针对ACCESS2000环境的,对于ACCESS97,需要改为:Provider=Microsoft.Jet.OLEDB.3.51; }
}
}
catch(_com_error e)///捕捉异常
{
CString errormessage;
errormessage.Format("连接数据库失败!/r/n错误信息:%s",e.ErrorMessage());
AfxMessageBox(errormessage);///显示错误信息
return FALSE;
}
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
CADOTest1Dlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
int CADOTest1App::ExitInstance()
{
if(m_pConnection->State)
m_pConnection->Close(); ///如果已经打开了连接则关闭它
return CWinApp::ExitInstance();
}
3.使用 _ConnectionPtr 连接接口
public:
CADOTest1App();
_ConnectionPtr m_pConnection;
4.使用 _RecordsetPtr接口 m_pRecordset;
try
{
m_pRecordset.CreateInstance("ADODB.Recordset");
m_pRecordset->Open("SELECT * FROM users",_variant_t((IDispatch*)theApp.m_pConnection,true),adOpenStatic,adLockOptimistic,adCmdText);
m_bSuccess = TRUE;
while(!m_pRecordset->adoEOF)
{
vID = m_pRecordset->GetCollect("ID");
vUsername = m_pRecordset->GetCollect("username");
vOld = m_pRecordset->GetCollect("old");
vBirthday = m_pRecordset->GetCollect("birthday");
nItem=m_userlist.InsertItem(0xffff,(_bstr_t)vID);
m_userlist.SetItem(nItem,1,1,(_bstr_t)vUsername,NULL,0,0,0);
m_userlist.SetItem(nItem,2,1,(_bstr_t)vOld,NULL,0,0,0);
m_userlist.SetItem(nItem,3,1,(_bstr_t)vBirthday,NULL,0,0,0);
m_pRecordset->MoveNext();
}
}
catch(_com_error e)///捕捉异常
{
AfxMessageBox("读取数据库失败!");///显示错误信息
}
5.使用_CommandPtr接口
_CommandPtr接口返回一个Recordset对象,并且提供了更多的记录集控制功能。以下代码是使用_CommandPtr接口的方法:
_CommandPtr pCmd;
_RecordsetPtr MySet;
pCmd.CreateInstance(__uuidof(Command));
pCmd->ActiveConnection=MyDb; //_ConnectionPtr;
pCmd->CommandText="select * from table";
pCmd->CommandType=adCmdText;
pCmd->Parameters->Refresh();
MySet=pCmd->Execute(NULL,NUll,adCmdUnknown);
_variant_t TheValue=MySet->GetCollect("FIELD_1");
CString sValue=(char*)_bstr_t(TheValue);
6 数据类型的转换 COM对象和C++类型的数据。_vatiant_t _bstr_t