数据库名称为:CynosureDB,项目中用来存备份文件的文件夹:BackupFile
SQL语句:backup database CynosureBD to disk= @ filepath
数据访问方法:
public bool CopyData(string filepath)
{
Return ………………………………….;
}
页面按钮事件:
/// <summary>
/// 备份数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnBackUpData_Click(object sender, EventArgs e)
{
DateTime dt = getContextDate;
string FileTime = dt.ToFileTime().ToString();
string CreatePath = System.Web.HttpContext.Current.Server.MapPath((@"../BackupFile"));
string newName = "oce_" + FileTime + ".mdb";
string NewFileName = CreatePath + @"\" + newName;
//根据OID创建数据备份的文件夹
if (!Directory.Exists(CreatePath))
{
try
{
Directory.CreateDirectory(CreatePath);
}
catch (Exception ex)
{
HandleError(ex.Message, false);
return;
}
}
BackUpEntity backup = new BackUpEntity();
backup.BackUpDate = getContextDate;
backup.FileName = string.Format(@"CynosureDB_Bak_{0}.bak", dt.ToString("yyyy_MM_dd HH:mm:ss"));
backup.FilePath = string.Format(@"../BackupFile/{0}/oce_{1}.mdb", null, FileTime);
bool isSuc = true;
try
{
isSuc = BackUpBLL.CopyData(MapPath(backup.FilePath));
}
catch
{
File.Delete(NewFileName);
HandleError("数据备份", false);
return;
}
//添加备份记录到数据库
if (BackUpBLL.Add(backup) > 0)
{
HandleSuccess("备份成功", true);
}
else
{
HandleError("数据备份", false);
}
}
数据库还原SQL语句:
use master Alter Database CynosureBD Set Offline with Rollback IMMEDIATE
restore database CynosureBD from disk =@FilePath
Alter Database CynosureBD Set OnLine With rollback IMMEDIATE