using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
 
namespace lxw_mysql_helper
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }
 
        public String bakpath = @"D:\db_bak\";
        public String appDirecroty = @"C:\Program Files\MySQL\MySQL Server 8.0\bin";
        public String uname = "root";
        public String port = "3306";
        public String upass = "123456";
        public String dbname = "test";
        public String backupTime = "00:30";
 
        private void frmMain_Load(object sender, EventArgs e)
        {
            txtName.Enabled = false;
            txtPwd.Enabled = false;
            txtport.Enabled = false;
            txtBackUpPath.Enabled = false;
            txtMysqlPath.Enabled = false;
            txtBackUpTime.Enabled = false;
            txtdbName.Enabled = false;
            btnSelectBackUpPath.Enabled = false;
            btnSelectMysqlPath.Enabled = false;
 
        }
 
 
        /// <summary>
        /// 执行CMD命令
        /// </summary>
        /// <param name="workingDirectory">要启动的进程的目录</param>
        /// <param name="command">要执行的命令</param>
        public static void RunCMD(String workingDirectory, String command)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.WorkingDirectory = workingDirectory;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.WriteLine(command);
            p.StandardInput.WriteLine("exit");
        }
 
        /// <summary>
        /// 备份数据库
        /// </summary>
        public void bakup_db(string manual = "")
        {
            try
            {
                //String command = "mysqldump --quick --host=localhost --default-character-set=gb2312 --lock-tables --verbose  --force --port=端口号 --user=用户名 --password=密码 数据库名 -r 备份到的地址";
                //构建执行的命令
                StringBuilder sbcommand = new StringBuilder();
 
                StringBuilder sbfileName = new StringBuilder();
                if (manual == "manual")
                {
                    sbfileName.AppendFormat("manual_" + dbname + "_{0}", DateTime.Now.ToString("yyyyMMddHHmmss"));
                }
                else
                {
                    sbfileName.AppendFormat("auto_" + dbname + "_{0}", DateTime.Now.ToString("yyyyMMddHHmm"));
                }
                String fileName = sbfileName.ToString();
                //检查是否存在文件夹
                if (false == System.IO.Directory.Exists(bakpath))
                {
                    System.IO.Directory.CreateDirectory(bakpath);
                }
                String directory = bakpath + fileName + ".bak";
 
                //判断文件是否存在
                if (System.IO.File.Exists(directory) == true)
                {
                    return;
                }
 
                sbcommand.AppendFormat("mysqldump --quick --host=localhost --default-character-set=utf8 --lock-tables --verbose  --force --port={4} --user={0} --password={1} {2} -r \"{3}\"", uname, upass, dbname, directory, port);
                String command = sbcommand.ToString();
 
                ShowLog("备份命令:" + command);
                //获取mysqldump.exe所在路径
                //String appDirecroty = System.Windows.Forms.Application.StartupPath + "\\";
                RunCMD(appDirecroty, command);
 
                ShowLog(@"备份成功,路径:" + directory);
            }
            catch (Exception ex)
            {
                ShowErrorLog("数据库备份失败:" + ex.Message);
                // MessageBox.Show("数据库备份失败:" + ex.Message);
            }
        }
 
        /// <summary>
        /// 还原数据库
        /// </summary>
        public void recovery_db()
        {
            //string s = "mysql --port=端口号 --user=用户名 --password=密码 数据库名<还原文件所在路径";
            try
            {
                StringBuilder sbcommand = new StringBuilder();
 
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.InitialDirectory = bakpath;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    String directory = openFileDialog.FileName;
 
                    //在文件路径后面加上""避免空格出现异常
                    sbcommand.AppendFormat("mysql --host=localhost --default-character-set=utf8 --port={4} --user={0} --password={1} {2}<\"{3}\"", uname, upass, dbname, directory, port);
                    String command = sbcommand.ToString();
 
                    //获取mysql.exe所在路径
                    //String appDirecroty = System.Windows.Forms.Application.StartupPath + "\\";
 
                    DialogResult result = MessageBox.Show("您是否真的想覆盖以前的数据库吗?那么以前的数据库数据将丢失!!!", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result == DialogResult.Yes)
                    {
                        ShowLog("还原命令:" + command);
                        RunCMD(appDirecroty, command);
                        ShowLog("数据库还原成功");
                        MessageBox.Show("数据库还原成功!");
                    }
                }
 
            }
            catch (Exception ex)
            {
                ShowErrorLog("数据库还原失败:" + ex.Message);
                MessageBox.Show("数据库还原失败:" + ex.Message);
            }
        }
 
 
        private void btnBackUp_Click(object sender, EventArgs e)
        {
            bakup_db("manual");
        }
 
        private void btnRecovery_Click(object sender, EventArgs e)
        {
            recovery_db();
        }
 
        private void btnSelectMysqlPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            if (!string.IsNullOrEmpty(txtMysqlPath.Text))
            {
                path.SelectedPath = txtMysqlPath.Text;
            }
            path.ShowDialog();
            txtMysqlPath.Text = path.SelectedPath;
        }
 
        private void btnSelectBackUpPath_Click(object sender, EventArgs e)
        {
 
            FolderBrowserDialog path = new FolderBrowserDialog();
            if (!string.IsNullOrEmpty(txtBackUpPath.Text))
            {
                path.SelectedPath = txtBackUpPath.Text;
            }
            path.ShowDialog();
            txtBackUpPath.Text = path.SelectedPath;
        }
 
    
 
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (DateTime.Now.ToString("HH:mm") == backupTime)
            {
                bakup_db();
            }
        }
 
        void ShowLog(string log)
        {
            rtxtShow.AppendText(log + "\r\n");
        }
 
 
        void ShowErrorLog(string log)
        {
            //高亮显示
            rtxtShow.SelectionStart = rtxtShow.Text.Length;
            rtxtShow.SelectionLength = log.Length;
            rtxtShow.SelectionColor = Color.FromName("Red");
            rtxtShow.AppendText(log + "\r\n");
        }
 
 
 
        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (btnEdit.Text == "修改")
            {
                txtName.Enabled = true;
                txtPwd.Enabled = true;
                txtport.Enabled = true;
                txtBackUpPath.Enabled = true;
                txtMysqlPath.Enabled = true;
                txtdbName.Enabled = true;
                txtBackUpTime.Enabled = true;
                btnSelectBackUpPath.Enabled = true;
                btnSelectMysqlPath.Enabled = true;
                btnEdit.Text = "确定";
            }
            else if (btnEdit.Text == "确定")
            {
                uname = txtName.Text;
                upass = txtPwd.Text;
                dbname = txtdbName.Text;
                appDirecroty = txtMysqlPath.Text;
                bakpath = txtBackUpPath.Text;
                port = txtport.Text;
 
                backupTime = txtBackUpTime.Text;
                DateTime temp;
                if (!DateTime.TryParse(backupTime, out temp))
                {
                    ShowLog("备份时间格式错误,重置时间为00:30");
                    txtBackUpTime.Text = "00:30";
                    backupTime = txtBackUpTime.Text;
                }
 
                ShowLog("修改成功!");
                MessageBox.Show("修改成功!");
                btnEdit.Text = "修改";
 
                txtName.Enabled = false;
                txtPwd.Enabled = false;
                txtport.Enabled = false;
                txtBackUpPath.Enabled = false;
                txtMysqlPath.Enabled = false;
                txtBackUpTime.Enabled = false;
                txtdbName.Enabled = false;
            }
 
        }
    }
}
Copy the code