首先看头文件
#pragma once #import "c:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF") rename("BOF","adoBOF") #if !defined(AFX_ADOCONN_H__75D447E2_EABB_4A14_9762_DD826E28D19A__INCLUDED_) #define AFX_ADOCONN_H__75D447E2_EABB_4A14_9762_DD826E28D19A__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CAdoConn { public: _ConnectionPtr m_pConnection; _RecordsetPtr m_pRecordset; public: CAdoConn(void); virtual ~CAdoConn(void); void OnInitADOConn(); // 初始化—连接数据库 _RecordsetPtr& GetRecordSet(CString bstrSQL); // 执行查询 BOOL ExecuteSQL(CString bstrSQL); // 执行SQL语句,Insert Update _variant_t void ExitConnect(); }; #endif
下面是实现
#include "stdafx.h" #include "AdoConn.h" CAdoConn::CAdoConn(void) { } CAdoConn::~CAdoConn(void) { } void CAdoConn::OnInitADOConn() { ::CoInitialize(NULL); try { m_pConnection.CreateInstance("ADODB.Connection"); _bstr_t strConnect = "Provider=SQLOLEDB.1; Server=(local); Database=LibraryManageSys; user id=sa;password=root;"; m_pConnection->Open(strConnect,"","",adModeUnknown); } catch(_com_error e) { AfxMessageBox(e.Description()); } } _RecordsetPtr& CAdoConn::GetRecordSet(CString bstrSQL) { try { if(m_pConnection==NULL) OnInitADOConn(); m_pRecordset.CreateInstance(__uuidof(Recordset)); m_pRecordset->Open((_bstr_t)bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText); } catch(_com_error e) { AfxMessageBox(e.Description()); } return this->m_pRecordset; } BOOL CAdoConn::ExecuteSQL(CString bstrSQL) { try { if(m_pConnection == NULL) OnInitADOConn(); m_pConnection->Execute((_bstr_t)bstrSQL,NULL,adCmdText); return TRUE; } catch(_com_error e) { AfxMessageBox(e.Description()); return FALSE; } } void CAdoConn::ExitConnect() { if (m_pRecordset != NULL) m_pRecordset->Close(); m_pConnection->Close(); ::CoUninitialize(); }
把组件的初始化和取消初始化功能都集中在这个类中,屏蔽掉数据库使用的一些细节,当然功能很简单也就能实现各简单的增删改查,不过对于做一些小型应用来说帮助还是很大的。
时间: 2024-10-17 16:52:33