天天看点

自己写一个定时备份 mysql 的备份工具

mysql 备份工具(1)

  • ​​初​​
  • ​​mysql 备份工具(1)​​
  • ​​程序结构:​​
  • ​​代码:​​
  • ​​Form1.cs​​
  • ​​运行结果​​

希望能写一些简单的教程和案例分享给需要的人

mysql 备份工具(1)

最近遇到删库的事情,平时又没备份,非常的难受,写个工具,定时备份,如果出现回到解放前的事情,也有从容应对之法。

环境:需要先安装一个 mysql

系统:windows

工具:mysqldump.exe

主要是靠 mysqldump.exe

我这边写的只是一个定时任务。

程序结构:

代码:

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MysqlBak
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        // 当找不到文件或者拒绝访问时出现的Win32错误码
        const int ERROR_FILE_NOT_FOUND = 2;
        const int ERROR_ACCESS_DENIED = 5;


        // 通过命令行获取help显示信息
        void PrintDoc(string cmd)
        {
            Process process = new Process();
            try
            {
                process.StartInfo.UseShellExecute = false;   //是否使用操作系统shell启动 
                process.StartInfo.CreateNoWindow = true;   //是否在新窗口中启动该进程的值 (不显示程序窗口)
                process.StartInfo.RedirectStandardInput = true;  // 接受来自调用程序的输入信息 
                process.StartInfo.RedirectStandardOutput = true;  // 由调用程序获取输出信息
                process.StartInfo.RedirectStandardError = true;  //重定向标准错误输出
                process.StartInfo.FileName = "cmd.exe";
                process.Start();                         // 启动程序
                process.StandardInput.WriteLine(cmd); //向cmd窗口发送输入信息
                //process.StandardInput.WriteLine("txyf@mysql"); //向cmd窗口发送输入信息
                process.StandardInput.AutoFlush = true;
                // 前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
                process.StandardInput.WriteLine("exit");

                StreamReader reader = process.StandardOutput;//获取exe处理之后的输出信息
                string curLine = reader.ReadLine(); //获取错误信息到error
                while (!reader.EndOfStream)
                {
                    if (!string.IsNullOrEmpty(curLine))
                    {
                        showLog(curLine);
                    }
                    curLine = reader.ReadLine();
                }
                reader.Close(); //close进程

                process.WaitForExit();  //等待程序执行完退出进程
                process.Close();

            }
            catch (Win32Exception e)
            {
                if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
                {
                    showLog(e.Message + ". 检查文件路径.");
                }

                else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
                {
                    showLog(e.Message + ". 你没有权限操作文件.");
                }
            }
        }
        public void showLog(string msg)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(textBox2.Text);
            sb.Append("\r\n");
            sb.Append(string.Format("{0}:{1}", DateTime.Now, msg));
            textBox2.Text = sb.ToString();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            bkMysql();
        }

        private void bkMysql()
        {
            var dbip = textBox_dbip.Text;
            var dbprot = textBox_dbprot.Text;
            var dbuser = textBox_dbuser.Text;
            var password = textBox_dbpassword.Text;
            var dbname = textBox_dbname.Text;
            if (dbip.Length == 0 ||
                dbprot.Length == 0 ||
                dbuser.Length == 0 ||
                password.Length == 0 ||
                dbname.Length == 0)
            {
                MessageBox.Show("请先配置好参数");
            }

            //PrintDoc("help");
            string path = System.AppDomain.CurrentDomain.BaseDirectory;
            string bakpath = path + "bak";
            string bakName = bakpath + "\\" + dbname + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + " - all.sql";
            if (!Directory.Exists(bakpath))
            {
                Directory.CreateDirectory(bakpath);
            }

            string bf = $"{path}mysqldump.exe --host=\"{dbip}\" --port={dbprot} --user=\"{dbuser}\" --password=\"{password}\" --result-file=\"{bakName}\" --databases {dbname}";

            PrintDoc(bf);


            if (true)
            {
                SqlDirectory();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            bool isZD = false;
            if (DateTime.Now.ToString("mmss") == "0000")
            {
                isZD = true;
            }
            label1.Text = $"信息:{DateTime.Now}";
            if (button2.Text == "开启自动备份")
            {

            }
            else
            {
                switch (button2.Text)
                {
                    case "点击停止.":
                        button2.Text = "点击停止..";
                        break;
                    case "点击停止..":
                        button2.Text = "点击停止...";
                        break;
                    case "点击停止...":
                        button2.Text = "点击停止.";
                        break;
                    default:
                        break;
                }
                if (radioButton3.Checked)
                {
                    if (isZD)
                    {
                        bkMysql();
                    }
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {

            if (button2.Text == "开启自动备份")
            {
                button2.Text = "点击停止.";
            }
            else
            {
                button2.Text = "开启自动备份";
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string path = System.AppDomain.CurrentDomain.BaseDirectory;
            string bakpath = path + "bak";
            string bakName = bakpath + "\\" + "x1_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + " - all.sql";
            if (!Directory.Exists(bakpath))
            {
                Directory.CreateDirectory(bakpath);
            }
            System.Diagnostics.Process.Start(bakpath);
            //PrintDoc("start..");
        }

        private static TreeNode getRootNode(string dirname)//根据传入的文件夹地址,遍历所有的子目录和文件并生成节点
        {
            TreeNode node = new TreeNode(dirname);
            string[] dirs = Directory.GetDirectories(dirname);
            string[] files = Directory.GetFiles(dirname);

            foreach (string dir in dirs)
            {
                node.Nodes.Add(dir);
                getRootNode(dir);
            }
            foreach (string file in files)
            {

                TreeNode fnode = new TreeNode(file);
                node.Nodes.Add(fnode);
            }
            return node;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SqlDirectory();
        }

        private void SqlDirectory()
        {
            treeView1.Nodes.Clear();
            string path = System.AppDomain.CurrentDomain.BaseDirectory;
            string bakpath = path + "bak";
            if (!Directory.Exists(bakpath))
            {
                Directory.CreateDirectory(bakpath);
            }
            string[] files = Directory.GetFiles(bakpath);
            foreach (var item in files)
            {
                TreeNode fnode = new TreeNode(Path.GetFileName(item));
                treeView1.Nodes.Add(fnode);
            }
        }
    }
}      

运行结果