近期涉及到通過c# 對mysq數據庫的備份和附件功能
由於mysql 有類似的備份和附加的cmd命令。可是一直沒用過,今天實踐了下,感覺效率挺快。比自己寫的效率高。以下我列出c#調用mysql的備份和附加功能函數。
1.備份mysql數據庫
定義string strAddress = string.Format("mysqldump --host={0} --default-character-set=utf8 --lock-tables --routines --force --port=3306 --user={1} --password={2} --quick ", 連接的server名稱, username, 密碼);
string strDB=你須要備份的數據庫名稱。
this.mysqlPath = "C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin";
if (!string.IsNullOrEmpty(strDB))
{
sfd.Filter = "數據庫文件|*.sql";
sfd.FilterIndex = 0;
sfd.RestoreDirectory = true;
sfd.FileName = "BackUp-" + strDB + DateTime.Now.ToString("yyyyMMDDHHmmss") + ".sql";
if (sfd.ShowDialog() == DialogResult.OK)
{
string filePath = sfd.FileName;
string cmd = this.strAddress + strDB + " >" + filePath;
string result = RunCmd(m_mysqlPath, cmd);
if (result.Trim() == "")
{
Show("數據庫備份成功!", "提示", );
}
else
{
Show(result, "提示");
}
}
}
主要執行函數
private string RunCmd(string strPath, string strcmd)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.WorkingDirectory = strPath;
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(strcmd);
p.StandardInput.WriteLine("exit");
return p.StandardError.ReadToEnd();
}
運行就可以對選中數據庫進行備份。