【问题标题】:SqlCommand back up DatabaseSqlCommand 备份数据库
【发布时间】:2012-07-04 10:05:56
【问题描述】:

我有一个 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

【问题讨论】:

  • 能否在 sqlConnection1.Open() 上设置断点并检查 cmd.CommandText 的值(尤其是文件名路径)
  • 只是为了确保...备份存储在服务器上,而不是在发出命令的计算机上(除非两者是同一台机器)。
  • 备份在电脑上...
  • @Steve 这是命令 - BACKUP DATABASE DB_Tags_TestingTagBurner TO DISK=D:\New folder\DataBaseBackups\DB_Tags_TestingTagBurner.bak'

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      您应该在您的 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 获取操作的结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-20
        • 2018-12-01
        • 2021-12-08
        • 2020-09-04
        • 2015-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多