天天看點

自己寫一個定時備份 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);
            }
        }
    }
}      

運作結果