备份和还原数据库

备份数据库

  • Form层
if (!MessageHelper.ConfirmYesNo("确定要备份数据库文件吗?"))
                return;
string bakFile = string.Format("D:/BackUP/{0}.{1}.bak", ConfigurationManager.AppSettings["DbName"], DateTime.Now.ToString("yyyyMMdd"));
ExecutionResult res = backUpController.BackUpDB(ConfigurationManager.AppSettings["DbName"],bakFile);
if (res.Status)
{
     MessageHelper.ShowTips("数据库备份成功,请在数据库服务器上查看文件" + bakFile);
}
else
{
     MessageHelper.ShowError("数据库备份失败," + res.Message);
}
  • Dao层
public ExecutionResult BackUpDB(string dbName, string bakFile)
{
     string cmd = string.Format("USE MASTER; BACKUP DATABASE \"{0}\" TO DISK = '{1}'", dbName, bakFile);
     DBParameter dbParams = new DBParameter();
     ExecutionResult exeResult = sqlHelper.ExecuteUpdate(cmd, dbParams.GetParameters());
     return exeResult;
}

注:
form层中备份的文件夹D:/Backup自己定义,如果按此定义,在使用备份功能前需要首先在D盘手动新建 Backup 文件夹,否则会提示找不到路径,因此也可以在路径中取掉Backup,直接在D盘根目录创建,就不会存在此问题

还原数据库

  • Form层
if (string.IsNullOrWhiteSpace(txtFile.Text.Trim()))
{
      MessageHelper.ShowError("请输入或选择要还原的数据库文件路径");
      return;
}
string file = txtFile.Text.Trim();
ExecutionResult res = backUpController.RestoreDB(ConfigurationManager.AppSettings["DbName"],file);
if (res.Status)
{
     MessageHelper.ShowTips("数据库还原成功!");
}
else
{
     MessageHelper.ShowError("数据库还原失败," + res.Message);
}
  • Dao层
public ExecutionResult RestoreDB(string dbName, string bakFile)
{
     StringBuilder cmd = new StringBuilder();
     cmd.Append(string.Format(" USE MASTER; ALTER DATABASE [{0}] SET OFFLINE WITH ROLLBACK IMMEDIATE; ", dbName));
     cmd.Append(string.Format(" USE MASTER; RESTORE DATABASE \"{0}\" FROM DISK = '{1}' with replace;", dbName, bakFile));
     cmd.Append(string.Format(" USE MASTER; ALTER DATABASE [{0}] SET ONLINE;", dbName));
     DBParameter dbParams = new DBParameter();
     ExecutionResult exeResult = sqlHelper.ExecuteUpdate(cmd.ToString(), dbParams.GetParameters());
     return exeResult;
}

你可能感兴趣的:(备份和还原数据库)