Should I use ExecuteNonQuery for this db backup co

2020-03-31 04:59发布

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.

标签: c# ado.net
8条回答
迷人小祖宗
2楼-- · 2020-03-31 05:28

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.

查看更多
3楼-- · 2020-03-31 05:29

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.

查看更多
Deceive 欺骗
4楼-- · 2020-03-31 05:30
ExecuteNonQuery() 

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.

查看更多
何必那么认真
5楼-- · 2020-03-31 05:30

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.

查看更多
叼着烟拽天下
6楼-- · 2020-03-31 05:34

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

查看更多
可以哭但决不认输i
7楼-- · 2020-03-31 05:35

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.

查看更多
登录 后发表回答