C# Mysql數據庫備份、還原(MVC)

1、準備工做mysql

  1.電腦上要安裝上mysql,而且已經配置好了環境變量。sql

2、公共代碼數據庫

  1.配置文件(該節點只是爲備份、還原使用,數據庫鏈接字符串有另外的節點)app

  <connectionStrings>
    <add name="DapperConnection" connectionString="Database=testDta;data source=127.0.0.1;User Id=test;Password=123456;CharSet=utf8;port=3306" />
  </connectionStrings>

    2.獲取數據庫配置信息(全局變量)ui

 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.執行命令代碼spa

 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         }

3、備份代碼code

 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         }

4、還原代碼orm

 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         }

 5、小結blog

  1.我是在命令行輸入命令,若是成功了以後,再去程序中進行拼寫。

相關文章
相關標籤/搜索