一、准备工作
1.电脑上要安装上mysql,并且已经配置好了环境变量。
二、公共代码
1.配置文件(该节点只是为备份、还原使用,数据库连接字符串有另外的节点)
<connectionStrings> <add name="DapperConnection" connectionString="Database=testDta;data source=127.0.0.1;User Id=test;Password=123456;CharSet=utf8;port=3306" /> </connectionStrings>
2.获取数据库配置信息(全局变量)
1 //Mysql数据库连接字符串 2 static string dapperConnStr = ConfigurationManager.ConnectionStrings["DapperConnection"].ToString(); 3 static string[] connArray = dapperConnStr.Split(';'); 4 //获取Mysql的ip地址 5 static string ip = connArray[1].Substring(connArray[1].IndexOf('=') + 1); 6 //获取Mysql的用户名 7 static string user = connArray[2].Substring(connArray[2].IndexOf('=') + 1); 8 //获取Mysql的密码 9 static string password = connArray[3].Substring(connArray[3].IndexOf('=') + 1); 10 static string port = connArray[5].Substring(connArray[5].IndexOf('=') + 1); 11 //获取数据库 12 static string database = connArray[0].Substring(connArray[0].IndexOf('=') + 1);
3.执行命令代码
1 /// <summary> 2 /// 命令行操作 3 /// </summary> 4 /// <param name="command"></param> 5 /// <returns></returns> 6 private string RunCmd(string command) 7 { 8 Process p = new Process(); 9 10 p.StartInfo.FileName = "cmd.exe"; //确定程序名 11 p.StartInfo.Arguments = "/c " + command; //确定程式命令行 12 p.StartInfo.UseShellExecute = false; //Shell的使用 13 p.StartInfo.RedirectStandardInput = true; //重定向输入 14 p.StartInfo.RedirectStandardOutput = true; //重定向输出 15 p.StartInfo.RedirectStandardError = true; //重定向输出错误 16 p.StartInfo.CreateNoWindow = true; //设置置不显示示窗口 17 18 //mySql安装路径 19 string mysqlPath = GetMysqlPath() + "bin"; 20 p.StartInfo.WorkingDirectory = mysqlPath; 21 p.Start(); 22 23 p.StandardInput.WriteLine(command); //输入入要行的命令 24 25 p.StandardInput.WriteLine("exit"); //退出 26 return p.StandardError.ReadToEnd(); 27 }
4.获取mysql安装路径
1 /// <summary> 2 /// 获取MySql安装路径 3 /// </summary> 4 /// <returns></returns> 5 private string GetMysqlPath() 6 { 7 IDbConnection conn = new MySqlConnection(dapperConnStr); 8 9 string strsql = "select @@basedir as basePath from dual "; 10 string strPath = conn.Query<string>(strsql).FirstOrDefault(); 11 var o=conn.ExecuteScalar(strsql); 12 strPath = strPath.Replace("/", "\"); 13 return strPath; 14 }
三、备份代码
1 /// <summary> 2 /// 生成备份文件 3 /// </summary> 4 /// <returns></returns> 5 public ActionResult GenerateBackups() 6 { 7 try 8 { 9 using (NetEntities et = new NetEntities()) 10 { 11 string fileName = Request["fileName"] + ".sql"; 12 //此处需要查询数据库,以确保数据库名称的唯一性,省略 13 //还原数据库命令行示例:mysqldump -h 127.0.0.1 -utest -p123456 testDta > E:\work\download\Database_Backup\test.sql 14 string sqlAddress = "-h " + ip + " -u" + user + " -p" + password + " " + database; 15 using (SaveFileDialog sfd = new SaveFileDialog()) 16 { 17 sfd.Filter = "数据库文件|*.sql"; 18 sfd.FilterIndex = 0; 19 sfd.RestoreDirectory = true; 20 sfd.FileName = fileName; 21 22 string filePath = sfd.FileName; 23 string path = AppDomain.CurrentDomain.BaseDirectory + "download\Database_Backup\"; 24 string cmd = "mysqldump " + sqlAddress + " > " + path + filePath + ""; 25 string result = RunCmd(cmd); 26 27 } 28 return Json("备份成功"); 29 } 30 } 31 catch (Exception ex) 32 { 33 return Json("程序异常---"+ex.Message); 34 } 35 }
四、还原代码
1 /// <summary> 2 /// 还原备份 3 /// </summary> 4 /// <param name="fileName">备份数据库的名称</param> 5 /// <returns></returns> 6 public ActionResult RecoveryBackups(string fileName) 7 { 8 Response<string> _rsp = new Response<string>(); 9 try 10 { 11 using (NetEntities et = new NetEntities()) 12 { 13 StringBuilder sbcommand = new StringBuilder(); 14 15 OpenFileDialog openFileDialog = new OpenFileDialog(); 16 17 string directory = AppDomain.CurrentDomain.BaseDirectory + PublicInfo.Database_Backup + fileName; 18 //在文件路径后面加上""避免空格出现异常 19 //命令行完整示例:mysql --host=127.0.0.1 --default-character-set=utf8 --port=3306 --user=test --password=123456 testDta<E:\work\download\Database_Backup\test.sql 20 //命令(缩减)示例:mysql --host=10.10.50.23 --user=test --password=123456 testDta<E:\work\download\Database_Backup\test.sql(因为有些在my.ini文件中已经配置了默认项) 21 sbcommand.AppendFormat("mysql --host=" + ip + " --user=" + user + " --password=" + password + " " + database + "" + " <{0}", directory); 22 string command = sbcommand.ToString(); 23 RunCmd(command); 24 _rsp.code = (int)EnumCode.调用成功; 25 _rsp.sub_msg = "还原成功"; 26 27 return Json(_rsp); 28 } 29 } 30 catch (Exception ex) 31 { 32 _rsp.code = (int)EnumCode.程序异常; 33 _rsp.sub_msg = ex.Message; 34 LogHelper.WriteLog(classname, "RecoveryBackups", ex); 35 return Json(_rsp); 36 } 37 }
五、小结
1.我是在命令行输入命令,如果成功了之后,再去程序中进行拼写。