MySQL Timed Data Backup tool (C #)

Source: Internet
Author: User

The source of this post is http://blog.csdn.net/zhujunxxxxx/article/details/40124773 if reproduced please indicate the source. This article author original, email [email protected], if you have any questions, please contact the author

To ensure data security, we often have to back up the data. But in order to reduce our workload, I wrote a simple data backup tool to implement a scheduled backup database.

In fact, the program is very simple, the work of data backup is a few MySQL commands.

First look at the program's running interface


Can see the interface is very simple

We use the command line for data backup, so our program needs a function that executes the command line.

<summary>///CMD command///</summary>//        <param name= "workingdirectory" > directory of processes to be started </param>        //<param name= "command" > Command to execute </param> public        static void Startcmd (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");        }

Next is a function to back up the database

public void bakup_db () {try {//string command = "mysqldump--quick--host=lo Calhost--default-character-set=gb2312--lock-tables--verbose--force--port= port number--user= user name--password= password database name-r backup to the ground                Address ";                Build execution command StringBuilder Sbcommand = new StringBuilder ();                StringBuilder sbfilename = new StringBuilder (); Sbfilename.appendformat ("{0}", DateTime.Now.ToShortDateString ()). Replace ("-", ""). Replace (":", ""). Replace ("", "").                Replace ("/", "");                String fileName = sbfilename.tostring ();                String directory = Bakpath + filename+ ". Bak"; Sbcommand. AppendFormat ("mysqldump--quick--host=localhost--default-character-set=utf8--lock-tables--verbose--force--port=                3306--user={0}--password={1} {2}-r \ "{3}\" ", uname, UPass, dbname, directory); String command = Sbcommand.                ToString (); Gets the path where Mysqldump.exe is located//striNg Appdirecroty = System.Windows.Forms.Application.StartupPath + "\ \";            Startcmd (appdirecroty, command); } catch (Exception ex) {}}

Restoring a Database

 public void recovery_db () {//string s = "MySQL--port= port number--user= user name--password= password database name < restore file path";                try {StringBuilder Sbcommand = new StringBuilder ();                OpenFileDialog OpenFileDialog = new OpenFileDialog (); if (openfiledialog.showdialog () = = DialogResult.OK) {String directory = OpenFileDialog.                    FileName; After the file path, add "" to prevent the space from appearing abnormally sbcommand. AppendFormat ("MySQL--host=localhost--default-character-set=utf8--port=3306--user={0}--password={1} {2}<\" {3}                    \ "", uname,upass,dbname,directory); String command = Sbcommand.                    ToString ();                    Get mysql.exe path//string appdirecroty = System.Windows.Forms.Application.StartupPath + "\ \"; DialogResult result = MessageBox.Show ("Do you really want to overwrite the previous database?") Then the previous database data will be lost!!!            "," Warning ", Messageboxbuttons.yesno, messageboxicon.warning);        if (result = = Dialogresult.yes) {startcmd (appdirecroty, command); MessageBox.Show ("Database restore succeeded!")                    "); }}} catch (Exception ex) {MessageBox.Show ("Database restore failed!            "); }        }

In order to achieve scheduled backups, we are using a Timer component to enable scheduled data backups

private void Timer1_Tick (object sender, EventArgs e)        {            int h = DateTime.Now.Hour;            if (h = = Hour)            {                bakup_db ();            }        }

Give the complete code

Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing; Using system.text;using system.windows.forms;using system.diagnostics;namespace mysqlbak{public partial class Form1:        Form {//path to backup file public String bakpath= "d:\\db_bak\\";        Public String Appdirecroty = @ "C:\Program Files (x86) \mysql\mysql Server 6.0\bin";        Public String uname = "root";        Public String UPass = "root";        Public String dbname = "losscar_db";        public int hour=18;            Public Form1 () {InitializeComponent (); Timer1.            interval=1000*10; Timer1.            Start (); Txt_uname.            Text = uname; Txt_upass.            Text = UPass; Txt_dbname.            Text = dbname; Txt_bakpath.            Text = Bakpath; Txt_mysql.            Text = Appdirecroty; Txt_hour. Text = Hour.        ToString (); }///<summary>//CMD command///</summary>//<param name= "workingdirectory" > Directory of Processes to start </param>//<param name= "command" > Commands to execute </param>            public static void Startcmd (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"); private void Btn_bak_click (object sender, EventArgs e) {try {//stri ng command = "mysqldump--quick--host=localhost--default-character-set=gb2312--lock-tables--verbose--force--port= End Slogan--user= user name--password= password database name-RBack to the address ";                Build execution command StringBuilder Sbcommand = new StringBuilder ();                StringBuilder sbfilename = new StringBuilder (); Sbfilename.appendformat ("{0}", DateTime.Now.ToShortDateString ()). Replace ("-", ""). Replace (":", ""). Replace ("", "").                Replace ("/", "");                String fileName = sbfilename.tostring ();                String directory = Bakpath + FileName + ". Bak"; Sbcommand. AppendFormat ("mysqldump--quick--host=localhost--default-character-set=utf8--lock-tables--verbose--force--port=                3306--user={0}--password={1} {2}-r \ "{3}\" ", uname, UPass, dbname, directory); String command = Sbcommand.                ToString ();                Get mysqldump.exe path//string appdirecroty = System.Windows.Forms.Application.StartupPath + "\ \";                Startcmd (appdirecroty, command); MessageBox.Show (@ "Database has been successfully backed up to" + Directory + "file", "Prompt", MessageBoxButtons.OK, Messageboxicon.information); } catch (Exception ex) {MessageBox.Show ("Database backup failed!            ");  }} public void bakup_db () {try {//string command = "mysqldump --quick--host=localhost--default-character-set=gb2312--lock-tables--verbose--force--port= port number--user= user name--                password= Password database name-r backup to address ";                Build execution command StringBuilder Sbcommand = new StringBuilder ();                StringBuilder sbfilename = new StringBuilder (); Sbfilename.appendformat ("{0}", DateTime.Now.ToShortDateString ()). Replace ("-", ""). Replace (":", ""). Replace ("", "").                Replace ("/", "");                String fileName = sbfilename.tostring ();                String directory = Bakpath + filename+ ". Bak"; Sbcommand. AppendFormat ("mysqldump--quick--host=localhost--default-character-set=utf8--lock-tables--verbose--force--port= 3306--user={0}--password={1} {2}-r \ "{3}\" ", Uname, UPass, dbname, directory); String command = Sbcommand.                ToString ();                Get mysqldump.exe path//string appdirecroty = System.Windows.Forms.Application.StartupPath + "\ \";            Startcmd (appdirecroty, command);  } catch (Exception ex) {}} private void Btn_recovery_click (object sender,        EventArgs e) {recovery_db (); } public void recovery_db () {//string s = "MySQL--port= port number--user= user name--password= Password database name < original            The path of the piece;                try {StringBuilder Sbcommand = new StringBuilder ();                OpenFileDialog OpenFileDialog = new OpenFileDialog (); if (openfiledialog.showdialog () = = DialogResult.OK) {String directory = OpenFileDialog.                    FileName; After the file path, add "" to prevent the space from appearing abnormally sbcommand. AppendFormat ("MySQL--host=localhost--default-cHaracter-set=utf8--port=3306--user={0}--password={1} {2}<\ "{3}\" ", uname,upass,dbname,directory); String command = Sbcommand.                    ToString ();                    Get mysql.exe path//string appdirecroty = System.Windows.Forms.Application.StartupPath + "\ \"; DialogResult result = MessageBox.Show ("Do you really want to overwrite the previous database?") Then the previous database data will be lost!!!                    "," Warning ", Messageboxbuttons.yesno, messageboxicon.warning);                        if (result = = Dialogresult.yes) {startcmd (appdirecroty, command); MessageBox.Show ("Database restore succeeded!")                    "); }}} catch (Exception ex) {MessageBox.Show ("Database restore failed!            "); }} private void Btn_edit_click (object sender, EventArgs e) {if (btn_edit. text== "Modify") {Txt_dbname.                Enabled = true; Txt_uname. Enabled = true;                Txt_upass.                Enabled = true; Txt_bakpath.                Enabled = true; Txt_mysql.                Enabled = true; Txt_hour.                Enabled = true; Btn_edit.            Text = "OK"; } else if (Btn_edit. Text = = "OK") {uname = Txt_uname.                Text; UPass = Txt_upass.                Text; dbname = Txt_dbname.                Text; Appdirecroty = Txt_mysql.                Text; Bakpath = Txt_bakpath.                Text; hour = Int. Parse (Txt_hour.                Text);                MessageBox.Show ("Modified successfully!"); Btn_edit.                Text = "Modify"; Txt_dbname.                Enabled = false; Txt_uname.                Enabled = false; Txt_upass.                Enabled = false; Txt_bakpath.                Enabled = false; Txt_mysql.                Enabled = false; Txt_hour.            Enabled = false;            }} private void Timer1_Tick (object sender, EventArgs e) {int h = DateTime.Now.Hour;if (h = = Hour) {bakup_db (); }        }    }}



MySQL Timed Data Backup tool (C #)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.