一、准备工作

  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.获取数据库配置信息(全局变量)

         //Mysql数据库连接字符串
static string dapperConnStr = ConfigurationManager.ConnectionStrings["DapperConnection"].ToString();
static string[] connArray = dapperConnStr.Split(';');
//获取Mysql的ip地址
static string ip = connArray[].Substring(connArray[].IndexOf('=') + );
//获取Mysql的用户名
static string user = connArray[].Substring(connArray[].IndexOf('=') + );
//获取Mysql的密码
static string password = connArray[].Substring(connArray[].IndexOf('=') + );
static string port = connArray[].Substring(connArray[].IndexOf('=') + );
//获取数据库
static string database = connArray[].Substring(connArray[].IndexOf('=') + );

  3.执行命令代码

         /// <summary>
/// 命令行操作
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
private string RunCmd(string command)
{
Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; //确定程序名
p.StartInfo.Arguments = "/c " + command; //确定程式命令行
p.StartInfo.UseShellExecute = false; //Shell的使用
p.StartInfo.RedirectStandardInput = true; //重定向输入
p.StartInfo.RedirectStandardOutput = true; //重定向输出
p.StartInfo.RedirectStandardError = true; //重定向输出错误
p.StartInfo.CreateNoWindow = true; //设置置不显示示窗口 //mySql安装路径
string mysqlPath = GetMysqlPath() + "bin";
p.StartInfo.WorkingDirectory = mysqlPath;
p.Start(); p.StandardInput.WriteLine(command); //输入入要行的命令 p.StandardInput.WriteLine("exit"); //退出
return p.StandardError.ReadToEnd();
}

  4.获取mysql安装路径

         /// <summary>
/// 获取MySql安装路径
/// </summary>
/// <returns></returns>
private string GetMysqlPath()
{
IDbConnection conn = new MySqlConnection(dapperConnStr); string strsql = "select @@basedir as basePath from dual ";
string strPath = conn.Query<string>(strsql).FirstOrDefault();
var o=conn.ExecuteScalar(strsql);
strPath = strPath.Replace("/", "\\");
return strPath;
}

三、备份代码

         /// <summary>
/// 生成备份文件
/// </summary>
/// <returns></returns>
public ActionResult GenerateBackups()
{
try
{
using (NetEntities et = new NetEntities())
{
string fileName = Request["fileName"] + ".sql";
//此处需要查询数据库,以确保数据库名称的唯一性,省略
//还原数据库命令行示例:mysqldump -h 127.0.0.1 -utest -p123456 testDta > E:\\work\\download\\Database_Backup\\test.sql
string sqlAddress = "-h " + ip + " -u" + user + " -p" + password + " " + database;
using (SaveFileDialog sfd = new SaveFileDialog())
{
sfd.Filter = "数据库文件|*.sql";
sfd.FilterIndex = ;
sfd.RestoreDirectory = true;
sfd.FileName = fileName; string filePath = sfd.FileName;
string path = AppDomain.CurrentDomain.BaseDirectory + "download\\Database_Backup\\";
string cmd = "mysqldump " + sqlAddress + " > " + path + filePath + "";
string result = RunCmd(cmd); }
return Json("备份成功");
}
}
catch (Exception ex)
{
return Json("程序异常---"+ex.Message);
}
}

四、还原代码

         /// <summary>
/// 还原备份
/// </summary>
/// <param name="fileName">备份数据库的名称</param>
/// <returns></returns>
public ActionResult RecoveryBackups(string fileName)
{
Response<string> _rsp = new Response<string>();
try
{
using (NetEntities et = new NetEntities())
{
StringBuilder sbcommand = new StringBuilder(); OpenFileDialog openFileDialog = new OpenFileDialog(); string directory = AppDomain.CurrentDomain.BaseDirectory + PublicInfo.Database_Backup + fileName;
//在文件路径后面加上""避免空格出现异常
//命令行完整示例:mysql --host=127.0.0.1 --default-character-set=utf8 --port=3306 --user=test --password=123456 testDta<E:\\work\\download\\Database_Backup\\test.sql
//命令(缩减)示例:mysql --host=10.10.50.23 --user=test --password=123456 testDta<E:\\work\\download\\Database_Backup\\test.sql(因为有些在my.ini文件中已经配置了默认项)
sbcommand.AppendFormat("mysql --host=" + ip + " --user=" + user + " --password=" + password + " " + database + "" + " <{0}", directory);
string command = sbcommand.ToString();
RunCmd(command);
_rsp.code = (int)EnumCode.调用成功;
_rsp.sub_msg = "还原成功"; return Json(_rsp);
}
}
catch (Exception ex)
{
_rsp.code = (int)EnumCode.程序异常;
_rsp.sub_msg = ex.Message;
LogHelper.WriteLog(classname, "RecoveryBackups", ex);
return Json(_rsp);
}
}

 五、小结

  1.我是在命令行输入命令,如果成功了之后,再去程序中进行拼写。

C# Mysql数据库备份、还原(MVC)的更多相关文章

  1. MySQL数据库备份还原(基于binlog的增量备份)

    MySQL数据库备份还原(基于binlog的增量备份) 一.简介 1.增量备份      增量备份 是指在一次全备份或上一次增量备份后,以后每次的备份只需备份与前一次相比增加或者被修改的文件.这就意味 ...

  2. MySQL数据库备份还原

    本文以CentOS 7 yum安装的MariaDB-server5.5为例,说明MySQL的几种 备份还原方式 将服务器A(192.168.1.100)上的数据库备份,还原到B(192.168.1.2 ...

  3. 使用mysqldump进行mysql数据库备份还原

    mysqldump是mysql自带的备份还原工具,默认在安装目录的bin下 可通过cmd命令行启动,然后运行: 还原一个数据库: mysql -h 主机 -u 用户名 -p密码 数据库名 < 指 ...

  4. Linux下的Mysql数据库备份+还原

    数据库备份: root@debian-mm:/home/debian-mm# mysqldump -u root -p Account > Account.sql Enter password: ...

  5. 阿里云mysql数据库备份还原

    1.下载备份包 在rds的备份恢复中点击下载,在弹出的窗口中复制内网下载地址(前提是目标服务器与rds内网互通,否则请复制外网地址) 在目标服务器中执行如下命令进行下载: wget -c '复制的地址 ...

  6. [MySql] - 数据库备份还原

    导出数据库到SQL方法: mysqldump.exe -u[USERNAME] -p[PASSWORD] -h [IP] jira --lock-all-tables > c:\db.sql m ...

  7. c#mysql数据库备份还原

    1:引用dll MySql.Data.dll,   MySqlbackup.dll 2:建一个数据连接静态类 public static class mysql { public static str ...

  8. mysql 数据库 备份 还原

    参考资料: http://blog.51yip.com/mysql/139.html

  9. MySQL数据库备份和还原的常用命令

    其实很多情况下mysql备份就是采用了这些命令,例如: mysql导入和导出数据 linux自动定时备份web程序和mysql数据库 备份MySQL数据库的命令 mysqldump -hhostnam ...

  10. Mysql数据库备份和还原常用的命令

    Mysql数据库备份和还原常用的命令是进行Mysql数据库备份和还原的关键,没有命令,什么都无从做起,更谈不上什么备份还原,只有给系统这个命令,让它去执行,才能完成Mysql数据库备份和还原的操作,下 ...

随机推荐

  1. Go Programming Language 2

    [Go Programming Language 2] 1.In Go, the sign of the remainder is always the same as the sign of the ...

  2. InterpretML 微软可解释性机器学习包

    InterpretML InterpretML: A Unified Framework for Machine Learning Interpretability https://github.co ...

  3. MySql日期格式化(format)取值范围

  4. 小学四则运算口算练习app---No.2

    经过昨天的了解,虽然还是很懵,总要下手摸到鼠标来写第一个页面! 这是一开始设置出体数目和时间的页面,使用者根据提示进行相关设置即可! 代码如下: <?xml version="1.0& ...

  5. SpringBoot如何切换Redis默认库

    一些闲扯的话 我们清楚,Redis 尽管提供了 16 个索引库,但是每个数据库之间是隔离互不共享的,客户端默认连接使用的是 0 号数据库 . 注意:上方情况是基于单机 Redis 的,在集群模式下是没 ...

  6. (HK1-0)激活与配置摄像机

    HK使用手册 网络连接 激活与配置摄像机 网络摄像机可通过 SADP 软件.客户端软件和浏览器三种方式激活, 具体激活操作方式可参见<网络摄像机操作手册>. 1. 安装随机光盘或从官网下载 ...

  7. EasyUI前后端分离

    陈旧的开发模式 美工(ui工程师:出一个项目模型) java工程师:将原有的html转成jsp,动态展示数据 缺点: 客户需要调节前端的展示效果 解决:由美工去重新排版,重新选色.Vs前后端分离 美工 ...

  8. gnome3 调整标题栏高度

    适用于:gtk 3.20 + 1. 在用户主目录 -/.config/gtk3.0/ 下新建gtk.css文件: 2. 复制如下css值: headerbar.default-decoration { ...

  9. 讲题专用——线段树——优化DP

    题目链接:http://codevs.cn/problem/3342/ 题解: 最小化最大值:二分 二分最长空题段 令f[i]表示抄第i道题所花费的最小时间 状态转移方程:f[i]=min(f[j]) ...

  10. 团体项目(饱了嘛)_第一组_UML图

    UML图 需求分析报告 https://www.cnblogs.com/Clover-yee/p/11771395.html 类图 user(用户类):主要保存用户的基本信息 shop(商铺类):主要 ...