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;
        }

 

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