MFC ADO连接MYSQL实现增删改查 完整实现(MFC、C++通用)

前言:

转载请附上连接,本帖原创请勿照抄。

    在每次连接MySQL或者别的数据库的时候总有些不明白的地方,看着CSDN或者百度出来一堆答案总感觉有点杂乱无章,看多了实现了还好没实现就会感觉很烦。总的来说还是写的代码量少,没搞清楚。

    接下来为大家写完整实现的代码,简洁明了、直接了当。(有问题请留言看到会回复)

VS2017(C++项目、MFC、其他类型项目代码都可以直接拷过去把MFC的弹窗类型换一下就可以了)

配置数据源(32位和64位数据库和数据源最好一致推荐安装32位数据库)

进行测试确保可以连通

新建32位数据源就是32位数据源  如果32位和64位都建立则会显示32/64位

引入msado15.dll (默认msado15.dll所在路径如果一直提示找不到路径请把msado15.dll单独拷出来放Debug或Release目录下)

#include <afxwin.h>         // MFC 核心组件和标准组件
#include <afxext.h>         // MFC 扩展


#include <afxdisp.h>        // MFC 自动化类

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

#ifndef _AFX_NO_OLE_SUPPORT
#include <afxdtctl.h>           // MFC 对 Internet Explorer 4 公共控件的支持
#endif
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h>             // MFC 对 Windows 公共控件的支持
#endif // _AFX_NO_AFXCMN_SUPPORT

#include <afxcontrolbars.h>     // 功能区和控件条的 MFC 支持

.h文件定义初始化

//引入需要的头文件
#pragma once
#include <afx.h>
#include <afxdisp.h>
#include <comdef.h>
#include <VECTOR>
#import "msado15.dll" no_namespace rename("EOF","adoEOF") 
//初始化定义
public:
	_ConnectionPtr       m_pCon;
	_RecordsetPtr        m_pRec;
	_CommandPtr			 m_pCmd;
	afx_msg void OnBnClickedButton1();
	int ADOTest();

	//尾
	BOOL adoEOF() { return m_pRec->adoEOF; }
	//向下移动一条记录
	void MoveNext() { m_pRec->MoveNext(); }

.cpp实现连接数据库 并实现增删改查功能

//连接数据库	
CString strCmd = "", UserName = "", PassWord = "";
	UserName = "root";
	PassWord = "自己的密码";
        //DSN 配置数据源的名称  Server 数据库所在的ip  Database 数据库名  UID账号 PWD密码
	strCmd.Format"DSN=MYSQL_ADO;Server=%s;Database=%s;UID=%s;PWD=%s", "127.0.0.1", "db_animal", UserName, PassWord);
	m_pCon.CreateInstance(__uuidof(Connection));
	m_pRec.CreateInstance(__uuidof(Recordset));
	LPCTSTR ConnStr, UserID, PWD;
	ConnStr = strCmd; UserID = "root"; PWD = "自己的密码";
	try
	{
		m_pCon->Open(ConnStr, UserID, PWD, adModeUnknown);
	}
	catch (_com_error &e)
	{
		AfxMessageBox("连接数据库失败");
		return 0;
	}

进行添加操作

//----执行sql可以使用 m_pCon->Execute 也可以使用 m_pRec->Open 
//----为了做演示 查询添加使用m_pRec->Open  删除修改使用的是 m_pCon->Execute
//m_pCon->Execute(_bstr_t(strSql), 0, adCmdText);
//m_pRec->Open(ConnStr, m_pCon.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);


///----添加	

	//如果像添加多条记录则可以使用For循环,通过数组来实现多次添加
	CString AnimalID = "6";
	CString Cat = "b";
	CString Dog = "bb";
	CString Snake = "bbb";
	CString Rabbit = "bbbb";
	strCmd.Format(" INSERT INTO animal(AnimalID, Cat, Dog, Snake, Rabbit) values('%s', '%s', '%s', '%s','%s')", AnimalID, Cat, Dog, Snake, Rabbit);
	ConnStr = strCmd;   //CString直接转LPCTSTR 也可以ConnStr = (LPCTSTR)strCmd
	try
	{
		m_pRec->Open(ConnStr, m_pCon.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
	}
	catch (_com_error e)
	{
		AfxMessageBox("增加数据失败!");//显示错误信息
		return 0;
	}

进行删除操作

///----删除	
	
	CString strSql;
	strSql.Format(_T("DELETE FROM animal WHERE AnimalID = 6"));
	try
	{
		m_pCon->Execute(_bstr_t(strSql), 0, adCmdText);
	}
	catch (_com_error e)
	{

		MessageBox(e.Description()); //错误原因
		AfxMessageBox("删除数据失败!");//显示错误信息
		return 0;
	}

进行修改操作

///----修改	
	
	CString strSql = "", m_StringName="animal", m_StringPosition="小猫", m_StringNumber="蓝猫";
	strSql.Format(_T("UPDATE animal SET Cat = '%s' WHERE Cat = '%s' "), m_StringNumber, m_StringPosition );
	try
	{

		m_pCon->Execute(_bstr_t(strSql), 0, adCmdText);
	}
	catch (_com_error e)
	{
		AfxMessageBox("修改数据失败!");//显示错误信息
		return 0;
	}

进行查询操作

///-----查询
	
	//"select * from animal where AnimalID=1"  --根据animal表 查询AnimalID为1的数据
	strCmd.Format("select * from animal");   //--查询表内所有数据 
	ConnStr = strCmd;   //CString直接转LPCTSTR 也可以ConnStr = (LPCTSTR)strCmd
	try
	{
		m_pRec->Open(ConnStr, m_pCon.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
	}
	catch (_com_error e)
	{
		AfxMessageBox("打开表失败");
		return 0;
	}
	if (NULL == m_pRec)
	{         
		AfxMessageBox("查询数据出现错误!");
		return 0;  
	}   
	if(m_pRec->adoEOF)
	{  
		m_pRec->Close();
		AfxMessageBox("Thereis no records in this table");
		return 0; 
	}   
	_variant_t vAnimalID, vCat, vDog, vSnake, vRabbit;
	CString StrList[10][5]; int i = 0, j = 0;
	while(!m_pRec->adoEOF){
		//pRst->MoveFirst();//记录集指针移动到查询结果集的前面    
		vAnimalID = m_pRec->GetCollect(_variant_t("AnimalID"));
		vCat = m_pRec->GetCollect(_variant_t("Cat"));
		vDog = m_pRec->GetCollect(_variant_t("Dog"));
		vSnake = m_pRec->GetCollect(_variant_t("Snake"));
		vRabbit = m_pRec->GetCollect(_variant_t("Rabbit"));

		StrList[i][j++] = (LPSTR)(LPCSTR)(_bstr_t)vAnimalID; 
		StrList[i][j++] = (LPSTR)(LPCSTR)(_bstr_t)vCat;
		StrList[i][j++] = (LPSTR)(LPCSTR)(_bstr_t)vDog;
		StrList[i][j++] = (LPSTR)(LPCSTR)(_bstr_t)vSnake;
		StrList[i++][j++] = (LPSTR)(LPCSTR)(_bstr_t)vRabbit;
		j = 0;
		m_pRec->MoveNext();//下一条记录
	}

到这里MySQL增删改查以及完成,希望可以帮助到大家

例子下载链接(https://download.csdn.net/download/qq_37529913/11998817)

猜你喜欢

转载自blog.csdn.net/qq_37529913/article/details/103258570
MFC