VC++ 中ADO数据库的配置(Access2003-Access2007)

vc++ ADO数据库的配置(Access2003-Access2007

1.       首先在StdAfx.h中添加以下代码引入数据库:

#import "C:\\Program Files\\Common Files\\System\\ado\\msado15.dll" no_namespace rename("EOF","adoEOF")rename("BOF","adoBOF")

2.       然后再VC6.0VS2012中:插入->类,弹出一个窗口,类名叫做CADOConn,基类选择Generic Class(切记)

3.       然后在Class View中双击CADOConn,添加以下代码:

class CADOConn 

{

public:

CADOConn();

virtual ~CADOConn();

_RecordsetPtr m_pRecordset;//记录集指针

_ConnectionPtr m_pConnection;

void OnInitADOConn();//连接数据源

_RecordsetPtr& GetRecordset(_bstr_t bstrSQL);//获取打开的记录集指针

BOOL ExecuteSQL(_bstr_t bstrSQL);//执行SQL语句

void ExitConnect();//断开数据连接

 

};

4.       然后在File View中找到ADOCon.cpp文件,添加以下代码:

CADOConn::CADOConn()

{

 

}

 

CADOConn::~CADOConn()

{

 

}

 

void CADOConn::OnInitADOConn()

{

::CoInitialize(NULL);

try

{

        m_pConnection.CreateInstance("ADODB.Connection");

//      _bstr_t strConnect="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Med.mdb";//.mdb放在工程目录下  access2003

           _bstr_t strConnect ="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Med.mdb;Persist Security Info=False";//access2007

           m_pConnection->Open(strConnect,"","",adModeUnknown);

          

//      AfxMessageBox("数据库连接成功");

}

catch(_com_error e)

{

           AfxMessageBox("数据库连接失败");

}

}

void CADOConn::ExitConnect()

{

if(m_pRecordset!=NULL)//关闭记录集和断开数据源链接

           m_pConnection->Close();

::CoUninitialize();//释放COM环境

}

_RecordsetPtr& CADOConn::GetRecordset(_bstr_t bstrSQL)

{

//打开记录集,返回记录集指针

try

{

           if(m_pConnection==NULL)

                    OnInitADOConn();

           m_pRecordset.CreateInstance(__uuidof(Recordset));

           m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,\

                    adLockOptimistic,adCmdText);

}

catch (_com_error e)

{

           AfxMessageBox("记录集打开失败");

}

return m_pRecordset;

}

BOOL CADOConn::ExecuteSQL(_bstr_t bstrSQL)

{

try

{

           if(m_pConnection==NULL)

                    OnInitADOConn();

           m_pConnection->Execute(bstrSQL,NULL,adCmdText);

           return true;

}

catch (_com_error e)

{

           AfxMessageBox("不能打开记录集");

           return false;

}       

}

5.到此ADO数据库配置成功

 

posted @ 2014-04-30 16:28  ZhangAihua  阅读(268)  评论(0编辑  收藏  举报