2016-11-10 62 views
0

我的任務是爲Mysql Backup and Restore編寫c#.net代碼。C#MySqL恢復代碼

從服務器A取得備份並在服務器B上恢復。 寫入的代碼完全執行備份。但還原沒有發生。 我把相同的命令行從c#代碼放到命令提示符下執行。它從那裏恢復。但不是C#程序。 請幫助我確定我犯的錯誤。

static public void restore(string ip, string user, string password, string[] tblList, string sourcedb, string targetdb)  
{ 

    try 
    { 
     string basecmd; 
     basecmd = "/c mysql -h {0} -u {1} -p{2} {3} < {4}.sql"; 


     foreach (string s in tblList) 
     { 


      string db_tbl = sourcedb + "_" + s; 

      string cmd = String.Format(basecmd, ip, user, pass, targetdb, db_tbl); 
      //cmd = cmd + " >error1234.txt"; 
      System.Threading.Thread.Sleep(1000); 
      Console.WriteLine(cmd); 

      //System.Diagnostics.Process.Start("cmd.exe", cmd); 

      System.Diagnostics.ProcessStartInfo procStartInfo = 
       new System.Diagnostics.ProcessStartInfo("cmd", cmd); 

      procStartInfo.UseShellExecute = false; 
      procStartInfo.CreateNoWindow = true; 
      System.Diagnostics.Process proc = new System.Diagnostics.Process(); 
      proc.StartInfo = procStartInfo; 
      proc.Start(); 
      //sendSuccesEmail(); 
     } 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex); 
     Console.WriteLine("pause"); 
    } 


} 
+0

[MySQL數據的PHP定期備份(可能的重複http://stackoverflow.com/questions/38916163/php-regular-backup-of-mysql-數據) – e4c5

回答

0

我寫了一個C#機庫:MySqlBackup.NET
項目網址:https://github.com/adriancs2/MySqlBackup.Net

你可以試試看。下面是示例代碼,將完成任務

string dbSource = "server=192.168.1.100;user=root;pwd=1234;database=db1;"; 
string dbTarget = "server=192.168.1.200;user=root;pwd=1234;database=db1;"; 

string sqlDump = ""; 

// Backup from source database 
using (MySqlConnection conn = new MySqlConnection(dbSource)) 
{ 
    using (MySqlCommand cmd = new MySqlCommand()) 
    { 
     using (MySqlBackup mb = new MySqlBackup(cmd)) 
     { 
      conn.Open(); 
      cmd.Connection = conn; 

      sqlDump = mb.ExportToString(); 

      conn.Close(); 
     } 
    } 
} 

// Restore to target database 
using (MySqlConnection conn = new MySqlConnection(dbTarget)) 
{ 
    using (MySqlCommand cmd = new MySqlCommand()) 
    { 
     using (MySqlBackup mb = new MySqlBackup(cmd)) 
     { 
      conn.Open(); 
      cmd.Connection = conn; 

      mb.ImportFromString(sqlDump); 

      conn.Close(); 
     } 
    } 
}