VC++对Access数据库的操作(查询、插入、更新、删除等)

本文详细介绍了如何在VC++MFC环境中利用ADO方式访问Microsoft Access数据库,实现数据的存储、查询、插入、更新和删除等功能。通过实例演示,读者可以快速掌握如何在实际项目中应用这一技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Microsoft Office Access是由微软发布的关系数据库管理系统Access数据库常应用于小型软件系统中,比如:生产管理销售管理库存管理等各类企业管理软件,其最大的优点是:简单易学、使用灵活。

下面我们结合实例来详细说明,在VC++ MFC中,如何使用Access数据库文件进行数据的存储,如何实现对数据库中数据的查询、插入、更新和删除等操作。

(实例可在我的优快云资源中下载:http://download.youkuaiyun.com/detail/margin1988/8235865

首先,怎样创建一个可供VC++ MFC程序使用的Access数据库,并在该数据库中创建数据表呢?

第一步:打开Microsoft Office Access软件,点击“空白数据库”;


第二步:设置预创建空白数据库的文件名和文件类型(文件名:point32.mdb,文件类型:Microsoft Office Access 2000 数据库(*.mdb));


第三步:“创建”空白数据库;


第四步:为该数据库“设置数据库密码”(本例中密码设置为:1234);


第五步:在该数据库中创建一张表,例如:TestTab(编号,姓名,性别,年龄);


第六步:表创建完成后,保存并关闭数据库,然后将该数据库文件(point32.mdb)剪切到你的VC++程序debug或release目录中,则准备工作完成。

其次,在VC++ MFC中编写对该数据库中TestTab表进行数据查询、插入、更新、删除等操作的方法:

(1)导入才用ado方式访问Access数据库所需的DLL

#import "C:\Program Files\Common Files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")//ado访问ACCESS数据库必需

(2)在程序的入口函数中,初始化OLE以支持应用程序

AfxOleInit();

(3)获取应用程序(EXE)所在路径

CString path;//应用程序所在路径
char filepath[256];
char* pPath; 
GetModuleFileName(AfxGetInstanceHandle(),filepath,256);
pPath  = strrchr(filepath,'\\');
*pPath = 0;
path = filepath;

(4)创建数据库访问连接字符串

char* PtConnectStr;//数据库连接字符串
CString connstr =  "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
connstr += path;
connstr += "\\point32.mdb";
connstr += ";Jet OLEDB:Database Password='1234'";
PtConnectStr = connstr.GetBuffer(0);

(5)查询TestTab表中数据方法实现

//查询表中数据,并显示在List Control控件中
void CPoint32Dlg::ReadUserInfo()
{
	//select
	m_list.DeleteAllItems();//清空列表

	_ConnectionPtr m_pConnection;
	_RecordsetPtr m_pRecordset;

	try
	{
		m_pConnection.CreateInstance(__uuidof(Connection));
		m_pConnection->Open(PtConnectStr,"","",adModeUnknown);
	}
	catch(_com_error e)
	{
		CString errormessage;
		errormessage.Format("数据库连接失败.\r错误信息:%s",e.ErrorMessage());
		//AfxMessageBox(errormessage);
		MessageBox(errormessage,"连接失败",MB_ICONEXCLAMATION);
		if(m_pConnection->State)
			m_pConnection->Close();
		return;
	}

	try
	{

		//获取数据,放在数据集中
		CString cmd;
		cmd.Format("SELECT * FROM TestTab");

		m_pRecordset.CreateInstance("ADODB.Recordset");
		m_pRecordset->Open(cmd.GetBuffer(),
			_variant_t((IDispatch*)m_pConnection,true),
			adOpenStatic,
			adLockOptimistic,
			adCmdText);

		//处理数据,并显示
		_variant_t varbuffer;
		long index = 0;//注意:必须是long类型
		int countItem = 0;
		CString str;

		while(!m_pRecordset->adoEOF)
		{
			index = 0;
			//读ID号
			varbuffer = m_pRecordset->GetCollect(_variant_t(index));			
			if(varbuffer.vt!=VT_NULL)
			{
				str.Format("%d",varbuffer.lVal);
				m_list.InsertItem(countItem,str.GetBuffer());
			}
			//读其它的信息
			while(index < 3)
			{
				index++;
				varbuffer = m_pRecordset->GetCollect(_variant_t(index));
				if(varbuffer.vt!=VT_NULL)
				{
					str = (LPCTSTR)(_bstr_t)varbuffer;
					m_list.SetItemText(countItem,index,str.GetBuffer());
				}
			}

			m_pRecordset->MoveNext();
			countItem++;
		}
	}
	catch(_com_error &e)
	{
		//AfxMessageBox(e.Description());
		MessageBox(e.Description(),"数据库操作失败.",MB_ICONEXCLAMATION);
		if(m_pRecordset->State)
			m_pRecordset->Close();
		if(m_pConnection->State)
			m_pConnection->Close();
		return;
	}

	if(m_pRecordset->State)
		m_pRecordset->Close();
	if(m_pConnection->State)
		m_pConnection->Close();
}


(6)向TestTab表中插入数据方法实现

//向表中插入数据,并更新List Control控件中显示的数据
void CPoint32Dlg::OnBnClickedButton1()
{
	//insert
	_ConnectionPtr m_pConnection;
	_variant_t RecordsAffected;
	try
	{
		m_pConnection.CreateInstance(__uuidof(Connection));
		m_pConnection->Open(PtConnectStr,"","",adModeUnknown);
	}
	catch(_com_error e)
	{
		CString errormessage;
		errormessage.Format("数据库连接失败.\r错误信息:%s",e.ErrorMessage());
		MessageBox(errormessage,"       添加失败       ",MB_ICONEXCLAMATION);
		return;
	}
	try
	{
		CString strCmd="INSERT INTO TestTab(UName,UGender,UAge) VALUES('测试者','男','30')";

		for(int i=0;i<5;i++)
		{
			m_pConnection->Execute(strCmd.AllocSysString(),&RecordsAffected,adCmdText);
		}
	}
	catch(_com_error &e)
	{
		//AfxMessageBox(e.Description());
		MessageBox(e.Description(),"       添加失败       ",MB_ICONEXCLAMATION);
		if(m_pConnection->State)
			m_pConnection->Close();
		return;
	}
	if(m_pConnection->State)
		m_pConnection->Close();
	//MessageBox("添加成功!","消息");

	m_update.EnableWindow(TRUE);
	m_delete.EnableWindow(TRUE);

	ReadUserInfo();
}


(7)更新TestTab表中数据方法实现

//更新表中数据,并更新List Control控件的显示
void CPoint32Dlg::OnBnClickedButton3()
{
	// update
	_ConnectionPtr m_pConnection;
	_variant_t RecordsAffected;
	try
	{
		m_pConnection.CreateInstance(__uuidof(Connection));
		m_pConnection->Open(PtConnectStr,"","",adModeUnknown);
	}
	catch(_com_error e)
	{
		CString errormessage;
		errormessage.Format("数据库连接失败.\r错误信息:%s",e.ErrorMessage());
		MessageBox(errormessage,"       修改失败       ",MB_ICONEXCLAMATION);
		return;
	}
	try
	{
		CString strCmd="UPDATE TestTab SET [UGender]='女',[UAge]='20' WHERE [UName]='测试者'";

		m_pConnection->Execute(strCmd.AllocSysString(),&RecordsAffected,adCmdText);
	}
	catch(_com_error &e)
	{
		//AfxMessageBox(e.Description());
		MessageBox(e.Description(),"       修改失败       ",MB_ICONEXCLAMATION);
		if(m_pConnection->State)
			m_pConnection->Close();
		return;
	}
	if(m_pConnection->State)
		m_pConnection->Close();
	//MessageBox("修改成功!","消息");

	ReadUserInfo();
}


(8)删除TestTab表中数据及重置表中自动编号主键(key)方法现实

//删除表中数据、重置自动编号(从1开始),并更新List Control控件显示
void CPoint32Dlg::OnBnClickedButton4()
{
	// delete
	_ConnectionPtr m_pConnection;
	_variant_t RecordsAffected;
	try
	{
		m_pConnection.CreateInstance(__uuidof(Connection));
		m_pConnection->Open(PtConnectStr,"","",adModeUnknown);
	}
	catch(_com_error e)
	{
		CString errormessage;
		errormessage.Format("连接数据库失败!\r错误信息:%s",e.ErrorMessage());
		MessageBox(errormessage,"删除失败",MB_ICONEXCLAMATION);
		return;
	}
	try
	{
		//删除表中所有数据
		CString strCmd="DELETE FROM TestTab";

		m_pConnection->Execute(strCmd.AllocSysString(),&RecordsAffected,adCmdText);

		//重置表中自动编号ID,使其从1开始增加(必须先删除表中所有数据)
		strCmd="ALTER TABLE TestTab ALTER COLUMN ID COUNTER(1,1)";

		m_pConnection->Execute(strCmd.AllocSysString(),&RecordsAffected,adCmdText);
	}
	catch(_com_error &e)
	{
		//AfxMessageBox(e.Description());
		MessageBox(e.Description(),"删除失败",MB_ICONEXCLAMATION);
		if(m_pConnection->State)
			m_pConnection->Close();
		return;
	}
	if(m_pConnection->State)
		m_pConnection->Close();
	//MessageBox("删除成功!","完成");

	m_insert.EnableWindow(TRUE);
	m_update.EnableWindow(FALSE);
	m_delete.EnableWindow(FALSE);

	ReadUserInfo();
}

// shujukuDlg.cpp : implementation file // #include "stdafx.h" #include "shujuku.h" #include "shujukuDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CShujukuDlg dialog CShujukuDlg::CShujukuDlg(CWnd* pParent /*=NULL*/) : CDialog(CShujukuDlg::IDD, pParent) { //{{AFX_DATA_INIT(CShujukuDlg) m_shuju = _T(""); //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CShujukuDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CShujukuDlg) DDX_Text(pDX, IDC_EDIT1, m_shuju); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CShujukuDlg, CDialog) //{{AFX_MSG_MAP(CShujukuDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_WM_TIMER() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CShujukuDlg message handlers BOOL CShujukuDlg::OnInitDialog() { CDial
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值