SqlCommand备份数据库

时间:2012-07-04 10:05:56

标签: c# sql database sql-server-2008 tsql

我有一个c#winforms应用程序(.net 2框架)。 我需要从我的应用程序备份数据库。 我试图通过异步执行SqlCommand来做到这一点。 代码执行时没有异常,但我没有在目的地获得.bak文件......

这是代码:

#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

3 个答案:

答案 0 :(得分:3)

在SQL备份行中,您似乎在备份文件路径的开头缺少单引号。

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

答案 1 :(得分:1)

您应该在SqlCommand实例上调用EndExecuteNonQuery(),以便抛出任何最终异常,从而了解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()循环块。

引用MSDN

  

对于每次调用BeginOperationName,应用程序也应该调用   EndOperationName获取操作的结果。

答案 2 :(得分:1)

尝试隔离问题的两个建议:

1)获取结果字符串(您在SqlCommand上执行的字符串,并在SQL Server上手动运行,以确保备份commnad正确。

2)尝试使用常规ExecuteNonQuery的同步命令来查看是否收到SQL Server异常