简体   繁体   中英

MySQL database backup using C#

I am trying to take back up of a mysql database. the code i am created is

ProcessStartInfo proc = new ProcessStartInfo();
string cmd = string.Format(@"-u{0} -p{1} -E -R -h{2} {3}", UserName, PWD, hostname, dbname);
proc.FileName = "Path to mysqldump.exe";
proc.RedirectStandardInput = false;
proc.RedirectStandardOutput = true;
proc.Arguments = cmd;
proc.UseShellExecute = false;
Process p = Process.Start(proc);
string res;
res = p.StandardOutput.ReadToEnd();
file.WriteLine(res);
p.WaitForExit();
file.Close();

The problem is it working correctly when the database size is small but i am getting Out Of Memory Exception when i am trying to take back up of large database (Approximately 800 MB ).

Instead of reading the standard output in C# why don't you write it directly to file through the command line?

I typically take my mysqldumps using the following command. It works in both Windows and Linux.

mysqldump -u{user} -p{password} --routines --triggers --result-file={dest_filename} {dbname}

-OR-

mysqldump -u{user} -p{password} --routines --triggers {dbname} > {dest_filename}

The Out of memory exception you encountered would probably have been caused when trying to read the entire output of mysqldump to memory in C# on the following line (typically happens when a string exceeds beyond a certain size).

res = p.StandardOutput.ReadToEnd();

Looks like very big string ate the memory.

Try to use OutputDataReceived event to write data in output file.

Here are two links with examples -

  1. Process.OutputDataReceived Event
  2. Process.BeginOutputReadLine Method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM