2012-07-04 3 views
1

C# winforms 응용 프로그램 (.net 2 프레임 워크)이 있습니다. 내 응용 프로그램에서 데이터베이스를 백업해야합니다. SqlCommand를 비동기 적으로 실행하여이 작업을 수행하려고합니다.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 (에 중단 점을 넣을 수있는 SQL 서버 예외를 받고 있는지 확인하기 위해 정기적 ExecuteNonQuery는과 동기 명령을 시도)와로 (cmd.CommandText의 값을 확인 특히 파일 이름 경로) – Steve

+2

그냥 확인하십시오 ... 백업은 서버에 저장되며 명령을 실행 한 컴퓨터에는 저장되지 않습니다 (두 컴퓨터가 동일한 경우 제외). –

+0

백업은 컴퓨터에 있습니다 ... –

답변

2

SQL 백업 라인에서 백업 파일의 경로 시작 부분에 작은 따옴표가 누락 된 것처럼 보입니다. 반드시 백업 commnad가 올바른지 확인하기 위해

1) 결과 문자열 (당신이하는 SqlCommand에서 실행되는 하나를 가져 오기 및 SQL 서버에서 수동으로 실행 :

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

당신은 던져하기 위해 귀하의하는 SqlCommand 인스턴스 EndExecuteNonQuery()를 호출해야합니다 :

코드입니다 ... 코드는 예외없이 실행하지만 내 대상에 .BAK 파일을 가져 해달라고 어떤 최종 예외 때문에 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를 호출해야합니다.

1

두 조언은 문제를 분리하려고합니다 .

2

)는