直接在cmd執行如下代碼:
mysqldump -h localhost -uroot -p123 --default-character-set=utf8 --opt --disable-keys --lock-all-tables -R --hex-blob TEST >D:\PM\bin\Debug\BackUp\TEST_20161212.sql
TEST為數據庫名稱
// 執行創建數據庫操作
this.GetExecute(G_Con, "create database if not exists NEWDB");
this.sqlAddress = " -h " + IP + " -u" + User + " -p" + Password + " NEWDB ";
// 數據庫的備份
private void btn_Dump_Click(object sender, EventArgs e)
{
using (SaveFileDialog sfd = new SaveFileDialog())
{
sfd.Filter = "數據庫文件|*.sql";
sfd.FilterIndex = 0;
sfd.RestoreDirectory = true;
sfd.FileName = "BackUp" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".sql";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string filePath = sfd.FileName;
string cmd = "mysqldump " + sqlAddress + " > \"" + filePath + "\"";
string result = RunCmd(cmd);
if (result.Trim() == "")
{
MessageBox.Show("數據庫備份成功!", "CMS", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(result, "CMS", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
//數據庫的還原
// 還原數據庫
private void btn_Import_Click(object sender, EventArgs e)
{
if (this.tb_Path.Text.Trim() == "")
{
MessageBox.Show("請選擇要恢復的文件!", "CMS", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//this.GetExecute(G_Con, "create database if not exists clothes");
string filePath = this.tb_Path.Text.Trim();
string cmd = "mysql " + sqlAddress + " < \"" + filePath + "\"";
string result = RunCmd(cmd);
if (result.Trim() == "")
{
MessageBox.Show("數據庫恢復成功!", "CMS", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(result, "CMS", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
// 命令行操作
private string RunCmd(string command)
{
//例Process
Process p = new Process();
p.StartInfo.FileName = "cmd.exe"; //確定程序名
p.StartInfo.Arguments = "/c " + command; //確定程式命令行
p.StartInfo.UseShellExecute = false; //Shell的使用
p.StartInfo.RedirectStandardInput = true; //重定向輸入
p.StartInfo.RedirectStandardOutput = true; //重定向輸出
p.StartInfo.RedirectStandardError = true; //重定向輸出錯誤
p.StartInfo.CreateNoWindow = true; //設置置不顯示示窗口
p.Start(); //00
p.StandardInput.WriteLine(command); //也可以用這種方式輸入入要行的命令
p.StandardInput.WriteLine("exit"); //要得加上Exit要不然下一行程式
//p.WaitForExit();
//p.Close();
//return p.StandardOutput.ReadToEnd(); //輸出出流取得命令行結果果
return p.StandardError.ReadToEnd();
}