2012-07-04 49 views
1

我有一個C#winforms應用程序(.net 2框架)。 我需要從我的應用程序備份數據庫。 我想通過異步執行一個SqlCommand來做到這一點。 的代碼並且無例外執行,但我沒有得到我的目的地.bak文件...SqlCommand備份數據庫

這是代碼:

#region backup DB using T-SQL command 

string connString = "Data Source=" + ConfigurationManager.AppSettings.Get("localhost_SQLEXPRESS") + ";Initial Catalog=" + db + ";UserID=" + ConfigurationManager.AppSettings.Get("user") + ";Password=" + ConfigurationManager.AppSettings.Get("password"); 
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connString); 
builder.AsynchronousProcessing = true; 
using (SqlConnection sqlConnection1 = new SqlConnection(builder.ConnectionString)) 
{ 
    using (SqlCommand cmd = new SqlCommand("BACKUP DATABASE " + db + " TO DISK=" + location + "\\" + ConfigurationManager.AppSettings.Get("DataBaseBackupsFolderName") + "\\" + db + ".bak'", sqlConnection1)) 
    {  
     sqlConnection1.Open();  
     IAsyncResult result = cmd.BeginExecuteNonQuery(); 

     while (!result.IsCompleted) 
     { 
      Thread.Sleep(100); 
     } 
    } 
} 
#endregion 
+0

你能穿上sqlConnection1.Open(斷點),並檢查cmd.CommandText的值(在特別是文件名路徑) – Steve

+2

只是爲了確保...備份存儲在服務器上,而不是在發出該命令的計算機上(除非兩者是同一臺計算機)。 –

+0

備份在計算機上... –

回答

2

在您的SQL備份行中,您似乎缺少備份文件路徑開頭處的單引號。

using (SqlCommand cmd = new SqlCommand("BACKUP DATABASE " + db + " TO DISK='" + location + "\\" + ConfigurationManager.AppSettings.Get("DataBaseBackupsFolderName") + "\\" +db + ".bak'", sqlConnection1)) 
1

你應該叫EndExecuteNonQuery()您的SqlCommand例如爲了扔任何最終的異常,從而瞭解什麼是不對您的SQL語句:

IAsyncResult result = cmd.BeginExecuteNonQuery(); 

// Wait for the command to complete 

result.AsyncWaitHandle.WaitOne(); 

// End the execution and throw any eventual exception 

cmd.EndExecuteNonQuery(result); 

正如你所看到的,我也換成你原來的Thread.Sleep()循環結構上的等待句柄更有效的等待comman d。

報價MSDN

每次調用BeginOperationName,應用程序還應該調用 EndOperationName獲得操作的結果。

1

兩個務必要儘量隔離問題:

1)獲取得到的字符串(你中SqlCommand執行一個SQL Server上手動運行它,以確保備份commnad是正確的。

2)嘗試同步命令與常規的ExecuteNonQuery,看看你得到一個SQL Server例外