ado.h // ADO.h: interface for the CADO class. // // #if !defined(AFX_ADO_H__75B10159_C8CC_4076_95CF_59403A8230BD__INCLUDED_) #define AFX_ADO_H__75B10159_C8CC_4076_95CF_59403A8230BD__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #import "c:/Program Files/Common Files/System/ado/msado15.dll" no_namespace rename("EOF","adoEOF") rename("BOF","adoBOF") class CADO { public: void CloseConn(); BOOL ExcuteSQL(_bstr_t bstrSQL); _RecordsetPtr& GetRecordset(_bstr_t bstrSQL); void OpenConnection(_bstr_t username, _bstr_t password); void InitAdoConn(); CADO(); virtual ~CADO(); private: _ConnectionPtr m_pConnection; _RecordsetPtr m_pRecordset; }; #endif // !defined(AFX_ADO_H__75B10159_C8CC_4076_95CF_59403A8230BD__INCLUDED_) ado.cpp // ADO.cpp: implementation of the CADO class. // // #include "stdafx.h" #include "ADOTest.h" #include "ADO.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif // // Construction/Destruction // CADO::CADO() { } CADO::~CADO() { } void CADO::InitAdoConn() { ::CoInitialize(NULL); try { // 创建Connection对象 m_pConnection.CreateInstance("ADODB.Connection"); } // 捕捉异常 catch(_com_error e) { // 显示错误信息 AfxMessageBox(e.Description()); } } void CADO::OpenConnection(_bstr_t username, _bstr_t password) { try { m_pConnection->Open("DSN=mysqlDSN;Server= localhost;Database=test", username, password, adModeUnknown); } catch(_com_error e) { // 显示错误信息 AfxMessageBox(e.Description()); } } _RecordsetPtr& CADO::GetRecordset(_bstr_t bstrSQL) { try { // 连接数据库,如果Connection对象为空,则重新连接数据库 if(m_pConnection==NULL) InitAdoConn(); // 创建记录集对象 m_pRecordset.CreateInstance(__uuidof(Recordset)); // 取得表中的记录 m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText); } // 捕捉异常 catch(_com_error e) { // 显示错误信息 AfxMessageBox(e.Description()); } // 返回记录集 return m_pRecordset; } BOOL CADO::ExcuteSQL(_bstr_t bstrSQL) { try { // 是否已经连接数据库 if(m_pConnection == NULL) InitAdoConn(); m_pConnection->Execute(bstrSQL,NULL,adCmdText); return TRUE; } catch(_com_error e) { AfxMessageBox(e.Description()); return FALSE; } } void CADO::CloseConn() { // 关闭记录集和连接 if (m_pRecordset != NULL) m_pRecordset->Close(); m_pConnection->Close(); ::CoUninitialize(); } 测试: void CADOTestDlg::OnBtnQuery() { // TODO: Add your control notification handler code here CADO ado; ado.InitAdoConn(); ado.OpenConnection((_bstr_t)"root", (_bstr_t)""); CString bstrSQL = "SELECT * FROM user WHERE id=1"; _RecordsetPtr rs = ado.GetRecordset((_bstr_t)bstrSQL); CString name; if (!rs->adoEOF) { name = (LPCTSTR)(_bstr_t)rs->GetCollect("name"); } MessageBox(name, "name", 0); //断开与数据库的连接 ado.CloseConn(); }