C++对MySQL数据库进行导出和导入操作

相信大家应该在网上看到很多利用SQL语句对MySQL数据库的表或者数据库本身进行导出和导入操作。在window环境下利用dos命令行导出数据库(我的mysq直接装在c盘根目录下下,其bin目录为:c:/mysql/bin):

1、执行MySQL数据库导出操作:

c:\mysql\bin>mysqldump -uroot -proot code_command > c:/code_command

2、导入Mysql数据库操作:

常用source 命令。进入mysql数据库控制台,如:mysql -u root -p ;mysql>use code_command ;然后使用source命令,后面参数为脚本文件(如这里用到的.sql):mysql>source c:/code_command.sql

最近在MFC环境下开发需要将导入和导出功能集成到应用程序中,查询了mysql的官方API,我没有找到对应的接口,查询了 hellokandy写的博客(https://blog.csdn.net/hellokandy/article/details/80497234),也没有找到对应的接口,因此采取利用c++调用dos窗口利用sql命令实现该功能,具体代码如下:

//导出数据库
void CDlgUserMangement::OnBtnExportSQL()
{
	//WinExec("cmd /c C:/mysql/bin/mysqldump.exe -hlocalhost -uroot -proot code_command > c:/q/bb.sql",SW_NORMAL);
	// TODO: 在此添加控件通知处理程序代码
	CString strFile="";
	CFileDialog dlgFile(TRUE,_T("*.sql"),NULL,OFN_HIDEREADONLY,_T("SQL File(*.sql)|*.sql"),NULL);
	
	if (IDOK==dlgFile.DoModal())
	{
		strFile=dlgFile.GetPathName();
		CString cmdSQL="cmd /c C:/mysql/bin/mysqldump.exe -hlocalhost -uroot -proot code_command > "+strFile;
		WinExec(cmdSQL,SW_HIDE);//SW_HIDE 不闪
		MessageBox("数据库导出成功!","提示");
	}

}


//导入数据库
void CDlgUserMangement::OnBtnImportSQL()
{

    char cmdstr[1000];
	char path[1024];
	FILE *f;
	CString strFile = "";
	CFileDialog dlgFile(true,_T("*.sql"),NULL,OFN_HIDEREADONLY,_T("SQL File(*sql)|*.sql"),NULL);
	if (dlgFile.DoModal() == IDOK)
	{
		strFile = dlgFile.GetPathName();
		sprintf(cmdstr,"@echo off\n");
		strcpy(path,"set str=\"C:\\mysql\\bin\\\"\n");
		sprintf(cmdstr,"%s%s\n",cmdstr,path);
		sprintf(cmdstr,"%s%s\n",cmdstr,"%str%mysql.exe -h localhost -uroot -proot code_command < "+strFile+"\n");
		f = fopen("c:\\mysql\\bin\\tmp.bat","w");
		fprintf(f,"%s",cmdstr);
		fclose(f);
		//WinExec("tmp.bat",SW_HIDE);//SW_HIDE 不闪
		ShellExecute(NULL,_T("open"),_T("c:\\mysql\\bin\\tmp.bat"),_T(""),NULL,SW_HIDE);
		//system("tmp.bat");
		remove("tmp.bat");
		MessageBox("数据库导入成功!","提示");
    }
}




 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值