2012-07-04 46 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例外