C#导出MYSQL单表数据

导出MySql数据库其中某张表的数据到.sql文件;

1             var sql = @" mysqldump  --user={用户名} --max_allowed_packet=1G --host=localhost --port=3306 --password={密码} --default-character-set=utf8 {数据库} {table名称}";
2             //mysqldump的路径
3             string mysqldump = "C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin";
4             //string filePath = strDBpath + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".sql";
5             string cmd = sql + " > " + exportFile;
6             RunCmd(mysqldump, cmd);

导出的文件不包含create database语句,自己手动插入:

1          private static void InsertCreate(string file)
2          {
3              string content = File.ReadAllText(file);
4              string create = "CREATE DATABASE  IF NOT EXISTS `{数据库}` /*!40100 DEFAULT CHARACTER SET utf8 */;\r\nUSE `{数据库}`;\r\n";
5              content = create + content;
6              File.WriteAllText(file, content);
7          }

MySQL的mysqldump程序执行函数:

 1         private static string RunCmd(string mysqldumPath, string strCmd)
 2         {
 3             System.Diagnostics.Process p = new System.Diagnostics.Process();
 4             p.StartInfo.FileName = "cmd.exe";
 5             p.StartInfo.WorkingDirectory = mysqldumPath;
 6             p.StartInfo.UseShellExecute = false;
 7             p.StartInfo.RedirectStandardInput = true;
 8             p.StartInfo.RedirectStandardOutput = true;
 9             p.StartInfo.RedirectStandardError = true;
10             p.StartInfo.CreateNoWindow = true;
11             p.Start();
12             p.StandardInput.WriteLine(strCmd);
13             p.StandardInput.WriteLine("exit");
14             return p.StandardError.ReadToEnd();
15         }

 

posted @ 2025-06-02 18:51  [春风十里]  阅读(21)  评论(0)    收藏  举报