2016-10-17 150 views
0

代码没有错误。但是当我备份时,文件的大小只有0kb或1kb。而当我恢复时什么都没有发生。所有数据仍然被删除。mySQL备份和还原c#

备份代码:

string path; 
path = "D:\\MySqlBackup"+ ".sql"; 
StreamWriter file = new StreamWriter(path); 


ProcessStartInfo psi = new ProcessStartInfo(); 
psi.FileName ="C:\\xampp\\mysql\\bin\\mysqldump.exe"; 
psi.RedirectStandardInput = false; 
psi.RedirectStandardOutput = true; 
psi.Arguments = "--user=root --password=database --database=hotelreservationandbillingsystem < D:\\MySqlBackup.sql"; 
psi.UseShellExecute = false; 

Process process = Process.Start(psi); 
string output; 
output = process.StandardOutput.ReadToEnd(); 
file.WriteLine(output); 
process.WaitForExit(); 
file.Close(); 
process.Close(); 
MessageBox.Show("Back Up Successfully!","Saved",MessageBoxButtons.OKCancel,MessageBoxIcon.Information); 

恢复代码:

string path; 
path = "D:\\MySqlBackup.sql"; 
StreamReader file = new StreamReader(path); 
string input = file.ReadToEnd(); 
file.Close(); 

ProcessStartInfo psi = new ProcessStartInfo(); 
psi.FileName = "C:\\xampp\\mysql\\bin\\mysqldump.exe"; 
psi.RedirectStandardInput = true; 
psi.RedirectStandardOutput = false; 
psi.Arguments = "--user=root --password=database --database=hotelreservationandbillingsystem < D:\\MySqlBackup.sql"; 
psi.UseShellExecute = false; 


Process process = Process.Start(psi); 
process.StandardInput.WriteLine(input); 
process.StandardInput.Close(); 
process.WaitForExit(); 
process.Close(); 
MessageBox.Show("Restored Successfully!", "Restored", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); 

回答

1

为什么你不应该尝试采取备份更简单的方法,并恢复可用的选项 MySqlBackup.NET - MySQL Backup Solution for C#

代码为Backu p

string constring = "server=localhost;user=root;pwd=qwerty;database=test;"; 
string file = "C:\\backup.sql"; 
using (MySqlConnection conn = new MySqlConnection(constring)) 
{ 
    using (MySqlCommand cmd = new MySqlCommand()) 
    { 
     using (MySqlBackup mb = new MySqlBackup(cmd)) 
     { 
      cmd.Connection = conn; 
      conn.Open(); 
      mb.ExportToFile(file); 
      conn.Close(); 
     } 
    } 
} 

而且恢复

string constring = "server=localhost;user=root;pwd=qwerty;database=test;"; 
string file = "C:\\backup.sql"; 
using (MySqlConnection conn = new MySqlConnection(constring)) 
{ 
    using (MySqlCommand cmd = new MySqlCommand()) 
    { 
     using (MySqlBackup mb = new MySqlBackup(cmd)) 
     { 
      cmd.Connection = conn; 
      conn.Open(); 
      mb.ImportFromFile(file); 
      conn.Close(); 
     } 
    } 
} 
+0

我需要添加引用?为MySqlBackup? – Frank

+0

是的,您需要先决条件 MySqlBackup.NET依靠以下组件来工作。 MySQL dot net连接器/网络(MySql.Data.DLL) 必须将此DLL的引用添加到您的项目中才能使MySqlBackup.NET正常工作。 MySql.Data.DLL由Oracle Corporation开发,获得GPL许可证(http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)的许可。 –