Skip to main content
 首页 » 编程设计

MFC笔记 MFC与Access连接的实现

2022年07月19日131zhenyulu

第一步,要连接数据库,首先要有数据源。这里我们选择的数据源是Access mdb文件。数据库名为DataBase,然后新建employees表,表的字段设计如下图:

 

 


第二步,我们要使用MFC与Access连接,还要显示最终结果如下图:

这里我们首先要先设计窗体,窗体各个控件的属性如下所示:

列表控件                     IDC_LIST1                  查看方式为:列表

三个标签                     分别命名为编号、姓名、学历

四个按钮控件

IDC_BUTADD            

IDC_BUTMOD

IDC_BUTDEL

IDC_BUTCLEAR

分别为下图所示的这些控件关联变量,详情看下图:

由于对于我们这个要实现的对话框应用程序中,还可以通过鼠标拖动列表控件的一列、还有选中一行记录,相关的文本框也会显示对应的值这些功能,我们需要在基于对话框类的OnInitDialog()函数中添加如下代码:

       m_Grid.SetExtendedStyle(LVS_EX_FLATSB

              |LVS_EX_FULLROWSELECT

              |LVS_EX_HEADERDRAGDROP

              |LVS_EX_ONECLICKACTIVATE

              |LVS_EX_GRIDLINES);

       m_Grid.InsertColumn(0,"编号",LVCFMT_LEFT,110,0);

       m_Grid.InsertColumn(1,"姓名",LVCFMT_LEFT,110,1);

       m_Grid.InsertColumn(2,"学历",LVCFMT_LEFT,110,2);

       AddToGrid();

第三步,要实现对数据库的操作,这里我们引用了windows系统自带的ADO动态链接库。

              导入的方法是:打开文件视图,找到StdAfx.h 文件,在里面添加如下代码:

#import "C:\Program Files\CommonFiles\System\ado\msado15.dll" no_namespace\

 rename("EOF","adoEOF")rename("BOF","adoBOF")//导入ADO动态链接库

第四步,还要自定义一个数据库操作类。方法步骤如下:

1.      新建一个ADO类。

设置好类信息,系统会为我们自动生成ADO.h 跟ADO.cpp两个文件,ADO.h中用来放置类的结构设计,ADO.cpp用来放置该类的成员函数的具体定义。

这里我们将ADO.h中放置如下代码:

// ADO.h: interface for the ADO class.

//

//

#if !defined(AFX_ADO_H__E0F8432E_F797_4979_8FB0_EAC60CA6C7F9__INCLUDED_)

#define AFX_ADO_H__E0F8432E_F797_4979_8FB0_EAC60CA6C7F9__INCLUDED_

#if _MSC_VER > 1000

#pragma once

#endif //_MSC_VER > 1000                                       

class ADO 

{

public:

   _ConnectionPtr m_pConnection;                               //连接对象指针

       _RecordsetPtr  m_pRecordset;                                 //记录集对象指针

public:

       ADO();

       virtual~ADO();

       voidOnInitADOConn();                                                 //连接数据库

       _RecordsetPtr&  OpenRecordset(CString sql);          //打开记录集

       voidCloseRecordset();                                             //关闭记录集

       voidCloseConn();                                                   //关闭数据库连接

       UINTGetRecordCount(_RecordsetPtr pRecordset);     //获得记录数 

};

#endif // !defined(AFX_ADO_H__E0F8432E_F797_4979_8FB0_EAC60CA6C7F9__INCLUDED_)

在ADO.cpp里放置如下代码:

// ADO.cpp: implementation of the ADO class.

//

//

#include "stdafx.h"

#include "UseAdo.h"

#include "ADO.h"

#ifdef _DEBUG

#undef THIS_FILE

static char THIS_FILE[]=__FILE__;

#define new DEBUG_NEW

#endif

//

// Construction/Destruction

//

ADO::ADO()

{

}

ADO::~ADO()

{

}

void ADO::OnInitADOConn()

{

       ::CoInitialize(NULL);

       try

       {

      m_pConnection.CreateInstance("ADODB.Connection");  //创建连接对象实例

          _bstr_t strConnect="DRIVER={MicrosoftAccess Driver (*.mdb)};\

                     uid=;pwd=;DBQ=DataBase.mdb;";

         m_pConnection->Open(strConnect,"","",adModeUnknown);//打开数据库

       }

       catch(_com_errore)

       {

              AfxMessageBox(e.Description());//弹出错误处理

       }

}

_RecordsetPtr&  ADO::OpenRecordset(CString sql)

{

       ASSERT(!sql.IsEmpty());                                                             //SQL语句不能为空

       try

       {

              m_pRecordset.CreateInstance(__uuidof(Recordset));//创建记录集对象实例

              m_pRecordset->Open(_bstr_t(sql),m_pConnection.GetInterfacePtr(),

                     adOpenDynamic,adLockOptimistic, adCmdText);      //执行SQL得到记录集

       }

       catch(_com_errore)                                                                            //捕获可能的异常

       {

              AfxMessageBox(e.Description());

       }

       returnm_pRecordset;

}

void ADO::CloseRecordset()

{

       if(m_pRecordset->GetState()== adStateOpen)    //判断当前的记录集状态

              m_pRecordset->Close();                             //关闭记录集

}

void ADO::CloseConn()

{

       m_pConnection->Close();                                                             //关闭数据库连接

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

}

UINT ADO::GetRecordCount(_RecordsetPtrpRecordset)

{

       intnCount = 0;                                                       //声明保存记录数的变量

       try{

              pRecordset->MoveFirst();                                 //将记录集指针移动到第一条记录

       }

       catch(...)                                                                              //捕捉可能出现的错误

       {

              return0;                                                                        //产生错误时返回0

       }

       if(pRecordset->adoEOF)                                                 //判断记录集中是否没有记录

              return0;                                                                        //无记录时返回0

       while(!pRecordset->adoEOF)                                  //当记录集指针没有指向最后时

       {

              pRecordset->MoveNext();                                 //将记录集指针移动到下一条记录

              nCount= nCount + 1;                                                     //记录个数的变量加1

       }

       pRecordset->MoveFirst();                                        //将记录集指针移动到第一条记录

       returnnCount;                                                                             //返回记录数

}

这样,用来实现与Access数据库的ADO类就实现了。

第五步,因为我们在该对话框应用程序中要使用到基于对话框类的成员AddToGrid函数。该函数的设计如下:

void CUseAdoDlg::AddToGrid()

{

       ADO m_Ado;

       m_Ado.OnInitADOConn();//连接数据库

       CStringSQL = "select * from employees order by 编号 desc"; //设置查询字符串

       m_Ado.m_pRecordset= m_Ado.OpenRecordset(SQL);//打开记录集

       while(!m_Ado.m_pRecordset->adoEOF)

       {

              m_Grid.InsertItem(0,"");

              m_Grid.SetItemText(0,0,(char*)(_bstr_t)m_Ado.m_pRecordset->GetCollect("编号"));

              m_Grid.SetItemText(0,1,(char*)(_bstr_t)m_Ado.m_pRecordset->GetCollect("姓名"));

              m_Grid.SetItemText(0,2,(char*)(_bstr_t)m_Ado.m_pRecordset->GetCollect("学历"));

              m_Ado.m_pRecordset->MoveNext();//将记录集指针移动到下一条记录

       }

       m_Ado.CloseRecordset();

       m_Ado.CloseConn();//断开数据库连接

}

第六步,接下来就剩下对各个具体的控件的功能函数的实现了。具体有5个控件要添加单击事件(四个按钮与一个列表控件)。添加方法是:直接双击要添加处理事件的控件,会弹出如下对话框:

分别对之前提到的五个控件单击事件添加代码,具体代码如下:

Butadd按钮的单击事件代码:

void CUseAdoDlg::OnButadd()

{

       //TODO: Add your control notification handler code here

       UpdateData(TRUE);

       if(m_ID.IsEmpty()|| m_Name.IsEmpty() || m_Culture.IsEmpty())

       {

              MessageBox("基础信息不能为空!");

              return;

       }

       ADO m_Ado;

       m_Ado.OnInitADOConn();

       CStringsql = "select * from employees";

       m_Ado.m_pRecordset= m_Ado.OpenRecordset(sql);

       try

       {

              m_Ado.m_pRecordset->AddNew();//添加新行

              m_Ado.m_pRecordset->PutCollect("编号",(_bstr_t)m_ID);

              m_Ado.m_pRecordset->PutCollect("姓名",(_bstr_t)m_Name);

              m_Ado.m_pRecordset->PutCollect("学历",(_bstr_t)m_Culture);

              m_Ado.m_pRecordset->Update();//更新数据表记录

              m_Ado.CloseRecordset();

              m_Ado.CloseConn();

       }

       catch(...)

       {

              MessageBox("操作失败");

              return;

       }

       MessageBox("添加成功");

       m_Grid.DeleteAllItems();//删除列表控件

       AddToGrid(); 

}

Butmod按钮的单击事件代码:

void CUseAdoDlg::OnButmod()

{

       //TODO: Add your control notification handler code here

       UpdateData(TRUE);

       if(m_ID.IsEmpty()|| m_Name.IsEmpty() || m_Culture.IsEmpty())

       {

              MessageBox("基础信息不能为空!");

              return;

       }

       intpos   = m_Grid.GetSelectionMark();

       ADO m_Ado;

       m_Ado.OnInitADOConn();

       CStringsql = "select * from employees";

       m_Ado.m_pRecordset= m_Ado.OpenRecordset(sql);

       try

       {

              m_Ado.m_pRecordset->Move((long)pos,vtMissing);

              m_Ado.m_pRecordset->PutCollect("编号",(_bstr_t)m_ID);

              m_Ado.m_pRecordset->PutCollect("姓名",(_bstr_t)m_Name);

              m_Ado.m_pRecordset->PutCollect("学历",(_bstr_t)m_Culture);

              m_Ado.m_pRecordset->Update();

              m_Ado.CloseRecordset();

              m_Ado.CloseConn();

       }

       catch(...)

       {

              MessageBox("操作失败");

              return;

       }

       MessageBox("修改成功");

       m_Grid.DeleteAllItems();

       AddToGrid();

}

Butdel按钮的单击事件代码:

void CUseAdoDlg::OnButdel()

{

       //TODO: Add your control notification handler code here

       intpos   = m_Grid.GetSelectionMark();

       ADO m_Ado;

       m_Ado.OnInitADOConn();

       CStringsql = "select * from employees";

       m_Ado.m_pRecordset= m_Ado.OpenRecordset(sql);

       try

       {

              m_Ado.m_pRecordset->Move(pos,vtMissing);

              m_Ado.m_pRecordset->Delete(adAffectCurrent);

              m_Ado.m_pRecordset->Update();

              m_Ado.CloseRecordset();

              m_Ado.CloseConn();

       }

       catch(...)

       {

              MessageBox("操作失败");

              return;

       }

       MessageBox("删除成功");

       OnButclear();

       m_Grid.DeleteAllItems();

       AddToGrid();

}

Butclear按钮的单击事件代码:

void CUseAdoDlg::OnButclear()

{

       //TODO: Add your control notification handler code here

       m_ID      = "";

       m_Name    = "";

       m_Culture= "";

       UpdateData(FALSE);

}

提示:Access数据库要放置在工程目录下,调试的时候才可以运行。如果单独要打开exe文件,必须要将数据库mdb文件放置在于exe文件夹一个目录下方可运行。

https://bbs.csdn.net/topics/30104508?utm_medium=distribute.pc_relevant_t0.none-task-discussion_topic-BlogCommendFromBaidu-1.channel_param&depth_1-utm_source=distribute.pc_relevant_t0.none-task-discussion_topic-BlogCommendFromBaidu-1.channel_param


本文参考链接:https://www.cnblogs.com/xihong2014/p/13660374.html
阅读延展