I have a method that allows me to kick off a back up of a data base. What I am wondering is if I should be using ExecuteNonQuery() in this context or if there is something better to use. Here is my code currently:
public static void RunBackup(string dbName, string filePath, string backupName, string connString)
{
using(SqlConnection objConnection = new SqlConnection(connString))
{
string commmandText = "BACKUP DATABASE @DBName TO DISK = @FilePath WITH NOFORMAT, NOINIT, NAME = @BackUpName, SKIP, NOREWIND, NOUNLOAD, STATS = 10";
SqlCommand objCommand = new SqlCommand(commmandText,objConnection);
objCommand.Parameters.AddWithValue("@dbName", dbName);
objCommand.Parameters.AddWithValue("@FilePath", filePath);
objCommand.Parameters.AddWithValue("@BackUpName", backupName);
objConnection.Open();
objCommand.ExecuteNonQuery();
objConnection.Close();
}
}
The one thing I am concerned about is being able to verify that the backup is complete and successful while handling time out issues for backups that take and extended time to complete.
ExecuteNonQuery
is the correct command to use.If you wish to receive more info about the restore process you should subscribe to the
InfoMessage
event of the SqlConnection object. That was you can capture all the "non-error" messages as well.This does look like the type of thing you should put in a stored procedure to do some error handling.
Also, have a look here to see it done in code.
should be fine to use here. What I would do is run a try catch around the using to catch any errors that might happen and deal with them appropiately.
I think ExecuteNonQuery is fine, but You should consider to user a timeout with Your query.
objCommand.CommandTimeout = 60*60; // for an hour or more
If You're using a desktop application, then for sure You should execute this query within asynchronous call.
ExecuteNonQuery means that the command doesn't return any data. It doesn't mean that it executes asynchronously or that you won't receive error information. It will block until the command finishes and return any errors that may occur
You should use
ExecuteNonQuery
when you do not what to receive any information from the database as a result of your call. If any error with happen during execute of the command you will get a corresponding exception.