Should I use ExecuteNonQuery for this db backup command

后端 未结 8 870
迷失自我
迷失自我 2021-01-17 03:26

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

相关标签:
8条回答
  • 2021-01-17 04:27

    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.

    0 讨论(0)
  • 2021-01-17 04:30

    To handle the issue of the long running query I ended up going with this:

        public static void RunBackup(string dbName, string filePath, string backupName, string connString)
        {
            string commmandText = "BACKUP DATABASE @DBName TO  DISK = @FilePath WITH NOFORMAT, NOINIT, NAME = @BackUpName, SKIP, NOREWIND, NOUNLOAD,  STATS = 10";
            SqlConnection objConnection = new SqlConnection(connString);
            try
            {
                SqlCommand objCommand = new SqlCommand(commmandText, objConnection);
                objCommand.Parameters.AddWithValue("@dbName", dbName);
                objCommand.Parameters.AddWithValue("@FilePath", filePath);
                objCommand.Parameters.AddWithValue("@BackUpName", backupName);
    
                objConnection.Open();
    
                IAsyncResult result = objCommand.BeginExecuteNonQuery();
                while (!result.IsCompleted)
                {
                    System.Threading.Thread.Sleep(100);
                }
    
    
                int count = objCommand.EndExecuteNonQuery(result);
             }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                objConnection.Close();
    
            }
    
        }
    

    This will allow me to execute the command without asyncronously without timeout issues. I will be adding some additional error handling etc in my final code set. I may do some additional work to see if I can get a better status returned at the end of the script that I can get via EndExecuteNonQuery or through an AsyncCallBack.

    0 讨论(0)
提交回复
热议问题