我有一个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
在您的SQL备份行中,您似乎在备份文件路径的开头缺少单引号。
using (SqlCommand cmd = new SqlCommand("BACKUP DATABASE " + db + " TO DISK='" + location + "\\" + ConfigurationManager.AppSettings.Get("DataBaseBackupsFolderName") + "\\" +db + ".bak'", sqlConnection1))