当前位置:网站首页>VS 2019 MFC 通过ACE引擎连接并访问Access数据库类库封装
VS 2019 MFC 通过ACE引擎连接并访问Access数据库类库封装
2022-06-12 07:25:00 【lzc881012】
网上有很多代码可以参考,大多数将的都是和#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")rename("BOF","adoBOF") 向关的内容。这些类容对VS2019之前的版本可能有用,但是对于VS2019来说帮助不大。VS2019放弃了老旧的“stdafx.h”预编译头文件,而改用“PCH.h”头文件。因此也是折腾了一段时间才解决了msado15.dll动态链接库的导入问题。
封装类库AdoControlAccess.h头文件
#include<odbcinst.h>
#include<afxdb.h>
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")rename("BOF","adoBOF")
class AdoControlAccess
{
public:
_ConnectionPtr m_Connection;
_RecordsetPtr m_Recorderset;
_CommandPtr m_CommandSql;
BOOL m_OpenDataBaseOpened;
public:
AdoControlAccess();
virtual~AdoControlAccess();
public:
_RecordsetPtr& GetRecordset(void);
_RecordsetPtr& OpenRecordSet(CString CmdSql);
void CloseConnectAndRecordset();
void AdoConnectionInit(_bstr_t strConnection, _bstr_t UserID, _bstr_t PassWord, long OpenAccessMode);
};
封装类库AdoControlAccess.CPP实现文件
#include "pch.h"
#include "AdoControlAccess.h"
AdoControlAccess::AdoControlAccess()
{
m_OpenDataBaseOpened = FALSE;
}
AdoControlAccess::~AdoControlAccess()
{
}
_RecordsetPtr& AdoControlAccess::GetRecordset(void)
{
return m_Recorderset;
}
_RecordsetPtr& AdoControlAccess::OpenRecordSet(CString CmdSql)
{
ASSERT(!CmdSql.IsEmpty());
try
{
m_Recorderset.CreateInstance("ADODB.Recordset");
if (m_Recorderset==NULL)
{
MessageBox(NULL, _T("RecordSet对象创建失败!请确认是否初始化了COM环境."), _T("信息提示:"), MB_OK | MB_ICONERROR);
printf("\n");
printf("RecordSetRecordSet对象创建失败!请确认是否初始化了COM环境!");
}
else
{
m_Recorderset->CursorLocation = adUseClient;
m_Recorderset->Open(_variant_t(CmdSql), m_Connection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
printf("\n");
printf("RecordSet对象已成功创建!");
}
}
catch (_com_error Error)
{
OutputDebugString(Error.Description());
MessageBox(NULL, Error.Description(), _T("信息提示:"), MB_OK | MB_ICONERROR);
}
return m_Recorderset;
}
void AdoControlAccess::CloseConnectAndRecordset()
{
if (m_Connection->State)
{
if (m_Recorderset != NULL)
{
m_Recorderset->Close();
m_Recorderset = NULL;
}
m_Connection->Close();
m_Connection = NULL;
}
}
void AdoControlAccess::AdoConnectionInit(_bstr_t strConnection,_bstr_t UserID,_bstr_t PassWord,long OpenAccessMode)
{
/*OpenAccessMode*/
/*adModeUnknown:
adModeRead : 只读
adModeWrite : 只写
adModeReadWrite : 可以读写
adModeShareDenyRead :阻止其它Connection对象以读权限打开连接
adModeShareDenyWrite :阻止其它Connection对象以写权限打开连接
adModeShareExclusive :阻止其它Connection对象打开连接
adModeShareDenyNone :允许其它程序或对象以任何权限建立连接*/
long nI = ::CoInitialize(NULL);
try
{
m_Connection.CreateInstance("ADODB.Connection");
m_Connection->ConnectionTimeout=5;
m_Connection->Open(strConnection, UserID, PassWord, OpenAccessMode);
m_OpenDataBaseOpened = TRUE;
printf("\n");
printf("已成功连接到Access数据库!");
}
catch (_com_error Error)
{
OutputDebugString(Error.Description());
MessageBox(NULL,Error.Description(),_T("信息提示:"),MB_OK|MB_ICONERROR);
m_OpenDataBaseOpened = FALSE;
}
}应用说明:应用程序头文件
#include"MacroDefinition.h"
#include"CMyStatic.h"
#include"CEditJF.h"
#include"CMyButton.h"
#include"ToolBarEx.h"
#include"AdoControlAccess.h"
#include"UserDataModifyDlg.h"
#pragma once
#define WM_USERDLG_SHUNTDOWN WM_USER+102
class CUserLogonDlg : public CDialogEx
{
DECLARE_DYNAMIC(CUserLogonDlg)
public:
CUserLogonDlg(CWnd* pParent = nullptr);
virtual ~CUserLogonDlg();
CWnd* m_Parent;
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_DIALOGUSERLOGON };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX);
void DrawTitleBar(CDC* pDC);
DECLARE_MESSAGE_MAP()
public:
CRect m_rtButtExit;
BOOL m_bCloseShow;
afx_msg void OnClose();
virtual BOOL OnInitDialog();
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
virtual LRESULT DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnNcHitTest(CPoint point);
afx_msg void OnNcLButtonDown(UINT nHitTest, CPoint point);
afx_msg void OnNcMouseMove(UINT nHitTest, CPoint point);
afx_msg void OpenAccessDataBase();
afx_msg void CloseAccessDataBaseAndRecorderset();
afx_msg void OnReadAdministratorInfo();
afx_msg void ModifyDataBaseRecordset(CString preModifyUserName,CString preModifyUserPwd,CString preModifyUserType);
afx_msg void AddNewRecordset(CString strUserName, CString strPwd, CString strUserType);
afx_msg void ErgodicAllUserInfo(CString InputUser, CString InputUserPwd, CString InputUserType);
CEditJF m_UserLogonName;
CEditJF m_UserLogonPassWord;
CMyStatic m_UserLogonDlgTitle;
CMyButton m_LogonMakeSure;
CMyButton m_UserLogOut;
CMyButton m_AddUser;
CMyButton m_UserModify;
CComboBoxXI m_LogonUserType;
CImageList m_LogonUserTypeImgList;
AdoControlAccess m_CUserDataBase;
_RecordsetPtr UserTableRecordset;
UserDataModifyDlg *m_CuserModifyDlg;
struct AdministratorInfo
{
CString AdName;
CString AdPwd;
CString AdType;
}AdminUser,PreLogonUser,TemUser,CurrentUser,UserWillBeModify, UpdateUserModifyByNewUser;
afx_msg void OnBnClickedButtonlogon();
afx_msg void OnBnClickedButtonlogonout();
afx_msg void OnBnClickedButtonadduser();
afx_msg void OnBnClickedButtonmodifyuser();
protected:
afx_msg LRESULT OnUsermodifydlgClose(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnUsermodifyUpdatedatabase(WPARAM wParam, LPARAM lParam);
};
连接说明: Access数据库默认的连接用户名为Admin
密码=数据库在建立时设置的访问密码
m_CUserDataBase.AdoConnectionInit("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=./User/UserDataBase.accdb;Persist Security Info=False;User ID=Admin;Jet OLEDB:Database Password= 密码", "", "", adModeUnknown);VS2019全面取消了SQL数据库以及Access数据库连接的连接向导,单保留了数据库连接工具。数据库连接工具在软件界面"工具"->“连接到数据库”里面可以找到。如下图所示。包括连接字符串也可以通过软件查看。

数据查询(CUserLogonDlg为应用程序类)
void CUserLogonDlg::OnReadAdministratorInfo()
{
OpenAccessDataBase();
if (m_CUserDataBase.m_OpenDataBaseOpened==TRUE)
{
UserTableRecordset = m_CUserDataBase.GetRecordset();
UserTableRecordset = m_CUserDataBase.OpenRecordSet(_T("SELECT UserTable.[UserName], UserTable.[UserPassWord], UserTable.[UserType] FROM UserTable where UserType='管理员'"));
if (UserTableRecordset->RecordCount > 0)
{
UserTableRecordset->MoveFirst();
AdminUser.AdName = UserTableRecordset->GetCollect("UserName");
AdminUser.AdPwd = UserTableRecordset->GetCollect("UserPassWord");
AdminUser.AdType = UserTableRecordset->GetCollect("UserType");
printf("\n");
printf("已成功获取到管理员账户!");
CloseAccessDataBaseAndRecorderset();
}
else
{
printf("\n");
printf("没有找到与管理员账户相关的信息!");
}
}
}数据更新
void CUserLogonDlg::ModifyDataBaseRecordset(CString preModifyUserName, CString preModifyUserPwd, CString preModifyUserType)
{
CString SqlCmd = _T("SELECT UserTable.[UserName], UserTable.[UserPassWord], UserTable.[UserType] FROM UserTable Where UserName=");
SqlCmd = SqlCmd + _T("'") + preModifyUserName+_T("'") ;
SqlCmd = SqlCmd + _T(" And ") + _T("UserPassWord=") + _T("'") + preModifyUserPwd + _T("'");
SqlCmd = SqlCmd + _T(" And ") + _T("UserType=") + _T("'") + preModifyUserType + _T("'");
OpenAccessDataBase();
if (m_CUserDataBase.m_OpenDataBaseOpened == TRUE)
{
UserTableRecordset = m_CUserDataBase.GetRecordset();
UserTableRecordset = m_CUserDataBase.OpenRecordSet(SqlCmd);
if (UserTableRecordset->RecordCount > 0)
{
UserTableRecordset->PutCollect("UserName", _variant_t(UpdateUserModifyByNewUser.AdName));
UserTableRecordset->PutCollect("UserPassWord", _variant_t(UpdateUserModifyByNewUser.AdPwd));
UserTableRecordset->PutCollect("UserType", _variant_t(UpdateUserModifyByNewUser.AdType));
UserTableRecordset->Update();
MessageBox(_T("当前被修改用户数据修改成功!。"), _T("信息提示:"), MB_OK | MB_ICONINFORMATION);
printf("\n");
printf("当前被修改用户数据修改成功。");
}
else
{
MessageBox(_T("数据库查询到当前要修改的用户不存在!请确认后重试。"), _T("信息提示:"), MB_OK | MB_ICONINFORMATION);
printf("\n");
printf("数据库查询到当前要修改的用户不存在!请确认后重试。");
}
CloseAccessDataBaseAndRecorderset();
}
}数据添加
void CUserLogonDlg::AddNewRecordset(CString strUserName,CString strPwd,CString strUserType)
{
if (strUserName == _T("") || strPwd == _T("") || strUserType == _T(""))
{
MessageBox(_T("用户名或密码或用户类型输入不能为空!请确认后重试。"), _T("信息提示:"), MB_OK | MB_ICONINFORMATION);
printf("\n");
printf("用户名或密码或用户类型输入不能为空!请确认后重试。");
return;
}
else
{
OpenAccessDataBase();
if (m_CUserDataBase.m_OpenDataBaseOpened == TRUE)
{
UserTableRecordset = m_CUserDataBase.GetRecordset();
UserTableRecordset = m_CUserDataBase.OpenRecordSet(_T("SELECT UserTable.[UserName], UserTable.[UserPassWord], UserTable.[UserType] FROM UserTable"));
if (UserTableRecordset->RecordCount > 0)
{
UserTableRecordset->MoveFirst();
for (int nCount = 0; nCount < UserTableRecordset->RecordCount; nCount++)
{
TemUser.AdName = UserTableRecordset->GetCollect("UserName");
if (TemUser.AdName== strUserName)
{
MessageBox(_T("要增加的用户已经存在!请确认后重试。"), _T("信息提示:"), MB_OK | MB_ICONINFORMATION);
printf("\n");
printf("要增加的用户已经存在!请确认后重试。");
break;
}
else if (strUserType == _T("管理员"))
{
MessageBox(_T("无法增加加管理员账户,请选择正确的用户类型。"), _T("信息提示:"), MB_OK | MB_ICONINFORMATION);
printf("\n");
printf("无法增加加管理员账户,请选择正确的用户类型。");
break;
}
else if (TemUser.AdName != strUserName&& strUserType != _T("管理员"))
{
UserTableRecordset->MoveNext();
}
if (UserTableRecordset->adoEOF)
{
if (TemUser.AdName != strUserName && strUserType != _T("管理员"))
{
UserTableRecordset->MoveLast();
UserTableRecordset->AddNew();
UserTableRecordset->PutCollect("UserName", _variant_t(strUserName));
UserTableRecordset->PutCollect("UserPassWord", _variant_t(strPwd));
UserTableRecordset->PutCollect("UserType", _variant_t(strUserType));
UserTableRecordset->Update();
UserTableRecordset->MoveFirst();
MessageBox(_T("新用户已成功添加到用户管理数据库!"), _T("信息提示:"), MB_OK | MB_ICONINFORMATION);
printf("\n");
printf("用户添加成功!");
break;
}
}
}
CloseAccessDataBaseAndRecorderset();
}
}
}
TemUser.AdName = _T("");
TemUser.AdPwd = _T("");
TemUser.AdType = _T("");
}
边栏推荐
- [yolo-v5 learning notes]
- Imx6q pwm3 modify duty cycle
- Missing getting in online continuous learning with neuron calibration thesis analysis + code reading
- Map to sort
- Golang 快速生成数据库表的 model 和 queryset
- d的自动无垃集代码.
- Adaptive personalized federated learning paper interpretation + code analysis
- Decoupling in D
- modelarts二
- Scons编译IMGUI
猜你喜欢

Imx6q pwm3 modify duty cycle

Personalized federated learning with exact stochastic gradient descent

Detailed explanation of addressing mode in 8086

Kali and programming: how to quickly build the OWASP website security test range?

RT thread studio learning (I) new project

Explain ADC in stm32

Construction of running water lamp experiment with simulation software proteus

2022年危险化学品经营单位安全管理人员特种作业证考试题库及答案

ROS dynamic parameter configuration: use of dynparam command line tool (example + code)

modelarts二
随机推荐
Gradient epic memory for continuous learning
1.3-1.9 summary
Improved schemes for episodic memory based lifelong learning
modelarts二
Summary of machine learning + pattern recognition learning (II) -- perceptron and neural network
Day 5 of pyhon
Modelarts培训任务1
RT thread studio learning (VII) using multiple serial ports
Complete set of typescript Basics
Summary of software testing tools in 2021 - unit testing tools
速度自关联函数—LAMMPS V.S MATALB
[image denoising] image denoising based on nonlocal Euclidean median (nlem) with matlab code
我人生中的第一个需求——Excel数据批量上传到数据库
Freshmen are worried about whether to get a low salary of more than 10000 yuan from Huawei or a high salary of more than 20000 yuan from the Internet
RT thread studio learning (I) new project
openwrt uci c api
Vscode outline preview cannot find file symbol
Golang quickly generates model and queryset of database tables
ROS dynamic parameter configuration: use of dynparam command line tool (example + code)
Node, topic, parameter renaming and global, relative and private namespaces in ROS (example + code)