C#中對MySQL數據庫進行備份還原操作

 一、執行cmd命令

        /// <summary>
        /// 執行cmd命令
        /// </summary>
        /// <param name="workingDirectory">要啓動的進程目錄</param>
        /// <param name="command">要執行的命令</param>
        public string StartCmd(string workingDirectory, string command)
        {
            string strOutput = "";

            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = "/C" + command;// "/c"標示執行完命令後退出
            p.StartInfo.WorkingDirectory = workingDirectory;
            p.StartInfo.UseShellExecute = false;//不啓用shell 啓動進程
            p.StartInfo.RedirectStandardInput = true;//重定向輸入
            p.StartInfo.RedirectStandardOutput = true;//重定向標準輸出
            p.StartInfo.RedirectStandardError = true;//重定向錯誤輸出
            p.StartInfo.CreateNoWindow = true;//不創建新窗口

            //如何判斷CMD語句是否執行成功???
            try
            {
                if (p.Start())//執行
                {
                    p.WaitForExit();//等待程序執行完,退出進程
                    strOutput = p.StandardOutput.ReadToEnd();//獲取返回值
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "軟件提示");
            }
            finally
            {
                if (p != null) p.Close();
            }
            return strOutput;
        }

二、備份整個數據庫

         其中m_UserId, m_Pwd, m_DataBaseName分別爲數據庫的用戶名、密碼、要備份的數據庫名。因爲是集成到數據庫操作類中,就沒有把參數單列出來。

        /// <summary>
        /// 備份數據庫
        /// </summary>
        /// <param name="strUserName">mySql用戶名</param>
        /// <param name="strPsw">mySql密碼</param>
        /// <param name="strDbName">要備份的數據庫名稱</param>
        public string BackUpDB()
        {
            string strFilePath = "";

            SaveFileDialog sf = new SaveFileDialog();
            sf.Filter = "數據庫文件(*.sql)|*.sql";
            sf.CheckPathExists = true;
            sf.AddExtension = true;//自動補充擴展名
            sf.OverwritePrompt = true;//若文件名存在,顯示警告
            sf.FileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".sql";//默認文件名

            if (sf.ShowDialog() == DialogResult.OK)
            {
                // mysqldump -u用戶名 -p密碼 -h主機 --datebases dbname1 dbname2...dbnamen>路徑
                //文件中以“--”開頭的是sql註釋,以“/*!40014”開頭的是關於MySQL服務器相關的註釋
                string strCmd = string.Format("mysqldump -u{0} -p{1} {2}>{3}", m_UserId, m_Pwd, m_DataBaseName,
                    sf.FileName);//中間不能有空格

                string strDbPath = GetMySqlInstallPath();//mySql安裝路徑
                try
                {
                    StartCmd(strDbPath, strCmd);
                    if (File.Exists(sf.FileName))
                    {
                        MessageBox.Show("備份成功!路徑:" + sf.FileName, "軟件提示");
                        strFilePath = sf.FileName;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
            }
            return strFilePath;
        }

三、還原數據庫

        /// <summary>
        /// 還原數據庫
        /// </summary>
        /// <param name="strUserName">mySql用戶名</param>
        /// <param name="strPsw">mySql密碼</param>
        /// <param name="strDbName">要備份的數據庫名稱</param>
        public string RestoreDB()
        {
            string strFileName = string.Empty;

            if (XtraMessageBox.Show("還原操作有風險,請確認數據庫已備份好!", "軟件提示", MessageBoxButtons.YesNo,
                MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                OpenFileDialog op = new OpenFileDialog();
                op.Title = "請選數據庫的文件";//對話框上的標題
                op.Filter = "數據庫文件(*.sql)|*.sql";
                op.CheckPathExists = true;
                op.RestoreDirectory = true;//是否記憶上次打開的目錄

                if (op.ShowDialog() == DialogResult.OK)
                {
                    //例:mysql -uroot -p1234 dbname<c:\aa.txt
                    string strCmd = string.Format("mysql -u{0} -p{1} {2}<{3}", m_UserId, m_Pwd, m_DataBaseName, op.FileName);

                    string strDbPath = GetMySqlInstallPath();//mySql安裝路徑
                    try
                    {
                        // StartCmd(path, "create database " + Databasename.Text.ToString()+";");
                        string strReturn = StartCmd(strDbPath, strCmd);
                        if (string.IsNullOrWhiteSpace(strReturn))
                        {
                            MessageBox.Show("還原成功!", "軟件提示");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message.ToString());
                    }
                }

                strFileName = op.FileName;
            }

            return strFileName;
        }

四、用到的其他函數

        /// <summary>
        /// 獲取mySql安裝路徑
        /// </summary>
        /// <returns></returns>
        public string GetMySqlInstallPath()
        {
            string strPath = "";
            string strSql = "SELECT @@basedir AS basePath From dual";
            object obj = GetSingleObject(strSql);

            if (obj != null)
            {
                strPath = obj.ToString();
                strPath = strPath.Replace("/", "\\");
                strPath += "bin";
            }

            return strPath;
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章