2012-02-16 128 views
0

嗨,我剛剛開始學習C#。我正在嘗試恢復.bak文件。但是我收到錯誤。由於數據庫正在使用中,無法獲得獨佔訪問權限。使用C#還原SQL Server 2005數據庫。回滾問題

我做了我的研究herehere都說我必須執行回滾。我不知道如何在恢復代碼中應用回滾。

public void RestoreDatabase(String RestorePath) 
    { 
     try 
     { 
      SqlConnection sqlCon = new SqlConnection("Data Source=RITZEL-PC\\SQLEXPRESS;User ID=NNIT-Admin;Password=password;Initial Catalog=master;"); 
      ServerConnection connection = new ServerConnection(sqlCon); 
      Server sqlServer = new Server(connection); 

      Restore restoreDB = new Restore(); 

      restoreDB.Database = "NNIT DB"; 
      restoreDB.Action = RestoreActionType.Database; 
      restoreDB.Devices.AddDevice(RestorePath, DeviceType.File); 

      restoreDB.ReplaceDatabase = true; // will overwrite any existing DB  
      restoreDB.NoRecovery = false; // NoRecovery = true; 

      restoreDB.SqlRestore(sqlServer); 

      MessageBox.Show("Restored"); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message + " " + ex.InnerException); 
     } 
    } 

回答

1

使用SMO您可以設置用戶訪問和回滾是這樣的:

Server sqlServer = new Server(connection); 

Database db = sqlServer.Databases["DbToRestore"]; 

if (db != null) 
{ 
    sqlServer.KillAllProcesses(db.Name); 
    db.DatabaseOptions.UserAccess = DatabaseUserAccess.Multiple; 
    db.Alter(TerminationClause.RollbackTransactionsImmediately); 
} 

Restore restoreDB = new Restore(); 
0

這是行不通的嗎?

SqlCommand cmd = new SqlCommand("ALTER DATABASE yourdatabasename SET MULTI_USER WITH ROLLBACK IMMEDIATE", sqlConn); 
cmd.ExecuteNonQuery(); 
+0

我會放在哪裏呢?還原之前restoreDB = new Restore();? – Ritzel 2012-02-16 09:55:27

+0

是的,它應該殺死所有到數據庫的連接 – 2012-02-16 09:57:09

+0

不,它不工作.. – Ritzel 2012-02-16 09:59:36

相關問題