2011-01-19 46 views
0

我尝试使用此代码作为控制台应用程序,这样我可以备份MyDatabase的自动化 我不知道因为我不知道自己做错了什么吧C#控制台应用程序备份mysql

static void Main(string[] args) 
{  
    try 
    { 
     DateTime backupTime = DateTime.Now; 
     int year = backupTime.Year; 
     int month = backupTime.Month; 
     int day = backupTime.Day; 
     int hour = backupTime.Hour; 
     int minute = backupTime.Minute; 
     int second = backupTime.Second; 
     int ms = backupTime.Millisecond; 

     String tmestr = backupTime.ToString(); 
     tmestr = "C:\\" + year + "-" + month + "-" + day + "-" + hour + "-" + minute + ".sql"; 
     StreamWriter file = new StreamWriter(tmestr); 
     ProcessStartInfo proc = new ProcessStartInfo(); 
     string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql"); 
     proc.FileName = "mysqldump"; 
     proc.RedirectStandardInput = false; 
     proc.RedirectStandardOutput = true; 
     proc.Arguments = cmd;//"-u root -p smartdb > testdb.sql"; 
     proc.UseShellExecute = false; 
     Process p = Process.Start(proc); 
     string res; 
     res = p.StandardOutput.ReadToEnd(); 
     file.WriteLine(res); 
     p.WaitForExit(); 
     file.Close(); 

    } 

    catch (IOException ex) 
    { 
     MessageBox.Show("Disk full or other IO error , unable to backup!"); 
    } 
} 
+0

请继续并接受您之前的一些问题......您是否尝试过调试您的代码?它不是我们的工作来完成你的工作。 – 2011-01-19 07:13:05

回答

0

什么样的的错误,至少这可能会改变。

string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql"); 

稍后,您的评论应该是-u root -p smartdb > testdb.sql"; 除了上述之外,缺少-u后的空间,所以我想将其更改为:

string cmd = string.Format(@"-u {0} -p {1} -h {2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql"); 
0

你为什么要创建一个StreamWriter,并试图获得mysqldump的输出,为什么不告诉mysqldump写入备份文件本身?

string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} > ""{4}"";", 
    "root", "", "localhost", "dbfile", tmestr); 
0

对于初学者我会改变你如何输出信息。您基本上打开了一个文件,以便您可以将备份实用程序的输出重定向到该文件。您的流程调用中的>就是为了这个目的。只需将您的"backup.sql"参数更改为tmestr即可。

此外,由于输出已被重定向到文件,您的进程将不会返回任何内容。但是因为我们现在已经将它转储到正确的路径,这应该是无关紧要的。

最后一项更改,在您的-u{0}之间加上一个空格,因此它是-u {0}。和-h {2}一样。

总结:

  • 删除StreamWriter和与之相关联的所有变量
  • 修改的过程参数使用`tmestr
  • 添加空格在cmd变量-u & -h
  • String.Format

而且你应该很好(假设找到mysqldump可执行文件不是问题。