C++對MySQL資料庫進行匯出和匯入操作
阿新 • • 發佈:2018-12-21
相信大家應該在網上看到很多利用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("資料庫匯入成功!","提示"); } }