ASP.NET遠(yuǎn)程備份恢復(fù)SQL Server數(shù)據(jù)庫

2010-08-28 10:52:10來源:西部e網(wǎng)作者:

///<summary>
      
///備份數(shù)據(jù)庫到本地磁盤
      
///</summary>
    
public bool BackUp(string BackUpFile)
    {
        try
        {
          
//第一步:在服務(wù)器上創(chuàng)建臨時文件夾
          ExecuteSql(@"master..xp_cmdshell 
'md C:\temp'");
          ExecuteSql(@"master..xp_cmdshell 
'del C:\temp\*.* /q'");
          
//第二步:備份數(shù)據(jù)庫到服務(wù)器目錄
          ExecuteSql(@"
backup database " + DataBaseName() + @" to disk='C:\temp\HSSY'");
          
//第三步:共享服務(wù)器的備份目錄
          ExecuteSql(@"master..xp_cmdshell 
'net share SQLDATABACK=C:\temp'");
          
//第四步:復(fù)制服務(wù)器上的備份文件到本地
          
File.Copy(@"\\" + ServerIP() + @"\SQLDATABACK\HSSY", BackUpFile,true);
          
          
return true;
        }
        catch (System.Data.SqlClient.SqlException E)
        {
          throw new Exception(E.Message);
        }
        finally
        {
          
//第五步:取消服務(wù)器共享目錄的共享
          ExecuteSql(@"master..xp_cmdshell 
'net share SQLDATABACK /delete'");
        }
    }

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

贊助商鏈接: