0

I'm tasked to write c#.net code for Mysql Backup and Restore.

The Backup is taken from Server A and restored on Server B. The code written, It executes back up perfectly. But the Restore is not happening. I put the same command line from c# code to command prompt and execute it. It restores from there. But not c# program. Please help me in identifying the mistake I'm making.

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");
    }


}
Broots Waymb
  • 4,713
  • 3
  • 28
  • 51
SaraDob
  • 77
  • 11
  • Possible duplicate of [PHP regular backup of mysql data](http://stackoverflow.com/questions/38916163/php-regular-backup-of-mysql-data) – e4c5 Nov 12 '16 at 02:26

1 Answers1

0

I have written a C# native library: MySqlBackup.NET
Project URL: https://github.com/adriancs2/MySqlBackup.Net

You can give it a try. Below is the sample code that will accomplish your task

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();
        }
    }
}
mjb
  • 7,649
  • 8
  • 44
  • 60