准备工作
(1)、引入ADO类
- #import "c:\program files\common files\system\ado\msado15.dll" \
- no_namespace \
- rename ("EOF", "adoEOF")
(2)、初始化COM
在MFC中可以用AfxOleInit();非MFC环境中用:
- CoInitialize(NULL);
- CoUnInitialize();
(3)#import 包含后就可以用3个智能指针了:_ConnectionPtr、_RecordsetPtr和_CommandPtr
1.连接和关闭数据库
(1)连接
例子:连接Access数据库
- AfxOleInit();//初始化
- HRESULT hr;
- try
- {
- hr = m_pConnection.CreateInstance("ADODB.Connection");///创建Connection对象
- if(SUCCEEDED(hr))
- {
- m_pConnection->ConnectionTimeout = 0;
- hr = m_pConnection->Open( "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb", "", "", adModeUnknown);
- //m_pConnection->PutDefaultDatabase ((_bstr_t)"DB"); //设置默认数据库
- m_pCommand.CreateInstance(__uuidof(Command));
- m_pCommand->CommandTimeout = 5;
- m_pCommand->ActiveConnection = m_pConnection;
- }
- }
- catch(_com_error e)///捕捉异常
- {
- CString errormessage;
- errormessage.Format(" 连接数据库失败! 错误信息:%s",e.ErrorMessage());
- AfxMessageBox(errormessage);///显 示错误信息
- }
(2)、关闭
- //如果数据库连接有效
- if( m_pConnection->State )
- m_pConnection->Close();
- m_pConnection = NULL;