///<summary>
///備份數據庫到本地磁盤
///</summary>
public bool BackUp(string BackUpFile)
{
try
{
//第一步:在服務器上創建臨時文件夾
ExecuteSql(@"master..xp_cmdshell 'md C:\temp'");
ExecuteSql(@"master..xp_cmdshell 'del C:\temp\*.* /q'");
//第二步:備份數據庫到服務器目錄
ExecuteSql(@"backup database " + DataBaseName() + @" to disk='C:\temp\HSSY'");
//第三步:共享服務器的備份目錄
ExecuteSql(@"master..xp_cmdshell 'net share SQLDATABACK=C:\temp'");
//第四步:復制服務器上的備份文件到本地
File.Copy(@"\\" + ServerIP() + @"\SQLDATABACK\HSSY", BackUpFile,true);
return true;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
finally
{
//第五步:取消服務器共享目錄的共享
ExecuteSql(@"master..xp_cmdshell 'net share SQLDATABACK /delete'");
}
}
/// <summary>
/// 從本地磁盤恢復數據庫
/// </summary>
public bool Restore(string RestoreFile)
{
try
{
//第零步:關閉用戶進程,防止其它用戶正在使用數據庫,導致數據恢復失敗
KillServerUser();
//第一步:在服務器上創建臨時文件夾
ExecuteSql(@"master..xp_cmdshell 'md C:\temp'");
ExecuteSql(@"master..xp_cmdshell 'del C:\temp\*.* /q'");
//第二步:共享服務器的恢復目錄
ExecuteSql(@"master..xp_cmdshell 'net share SQLRESTORE=C:\temp'");
//第三步:復制服務器上的備份文件到本地
File.Copy(RestoreFile, @"\\" + ServerIP() + @"\SQLRESTORE\HSSY",true);
//第四步:取消服務器共享目錄的共享
ExecuteSql(@"master..xp_cmdshell 'net share SQLDATABACK /delete'");
//第五步:恢復數據庫到服務器目錄
ExecuteSql(@"restore database " + DataBaseName()+ @" from disk='C:\temp\HSSY'");
return true;
}
catch (System.Data.SqlClient.SqlException E)
{
throw new Exception(E.Message);
}
finally
{
//第六步:取消服務器共享目錄的共享
//DbHelperSQL.ExecuteSql(@"master..xp_cmdshell 'net share SQLDATABACK /delete'");
}
}