2

私は 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
4

3 に答える 3

3

SQL バックアップ行では、バックアップ ファイルへのパスの先頭に一重引用符がないようです。

  using (SqlCommand cmd = new SqlCommand("BACKUP DATABASE " + db + " TO DISK='" + location + "\\" + ConfigurationManager.AppSettings.Get("DataBaseBackupsFolderName") + "\\" +db + ".bak'", sqlConnection1)) 
于 2012-07-04T10:14:04.507 に答える
1

問題を切り分けようとする2つのアドバイス:

1)結果の文字列(SqlCommandで実行している文字列を取得し、SQL Serverで手動で実行して、バックアップコマンドが正しいことを確認します。

2)通常のExecuteNonQueryとの同期コマンドを試して、SQLServer例外が発生しているかどうかを確認します

于 2012-07-04T10:15:53.867 に答える
1

EndExecuteNonQuery()最終的な例外をスローして、SQL ステートメントの何が問題なのかを理解するには、SqlCommand インスタンスを呼び出す必要があります。

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 も呼び出して操作の結果を取得する必要があります。

于 2012-07-04T10:11:32.490 に答える