Thursday, September 29, 2011

MySQL Database Back Up and Restore From Front end


protected void btnBackup_Click(object sender, EventArgs e)
    {
        DatabaseBackup("C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump.exe");

        
    }
    public void DatabaseBackup(string ExeLocation)
    {
        string tmestr = "";
        tmestr = "hostels_db" + "-" + DateTime.Now.ToShortDateString() + ".sql";
        tmestr = tmestr.Replace("/", "-");
        tmestr = "E:/" + tmestr;
        StreamWriter file = new StreamWriter(tmestr);
        ProcessStartInfo proc = new ProcessStartInfo();
        string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} --routines", "root", "root", "localhost", "hostels_db");
        ExeLocation = ExeLocation.Replace("\\", @"\");
        proc.FileName = ExeLocation;
        proc.RedirectStandardInput = false;
        proc.RedirectStandardOutput = true;
        proc.Arguments = cmd;
        proc.UseShellExecute = false;
        Process p = Process.Start(proc);
        string res;
        res = p.StandardOutput.ReadToEnd();
        #region
        //if (tmestr.Contains("*/;;"))
        //{
        //    tmestr.Replace("*/;;", "");
        //}
        //if (tmestr.Contains("/*!50003"))
        //{
        //    tmestr.Replace("/*!50003", "");
        //}
        //if (tmestr.Contains("*/ /*!50020"))
        //{
        //    tmestr.Replace("*/ /*!50020", "");
        //}
        #endregion
        file.WriteLine(res);
        p.WaitForExit();
        file.Close();
        Response.Write("Backup Completed...");

    }    
    protected void btnRestore_Click(object sender, EventArgs e)
    {
        DataBaseRestore("C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump.exe");
        //MySqlDataAdapter da = new MySqlDataAdapter("restore database from disk ",cn);
       
    }
    public void DataBaseRestore(string path)
    {
        string path1 = "E:\\hostels_db 952011.sql";
        path1 = path1.Replace("\\", @"\");
        StreamReader file = new StreamReader(path1);
        string input = file.ReadToEnd();
        file.Close();

        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = path;

        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = false;
        psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}", "root", "root", "localhost", "hostels_db");
        psi.UseShellExecute = false;


        Process process = Process.Start(psi);
        process.StandardInput.WriteLine(input);
        process.StandardInput.Close();
        process.WaitForExit();
        process.Close();
        Response.Write("Backup Restore Completed...");
    }

No comments:

Post a Comment