質問

Question: Is there a way to stop the Command.ExecuteNonQuery() before it is completed, without using timeout?

I have created a multi-threaded MySQL program that stores and run sql statements. Allowing a group of transactions run at the same time (because they do not modify the same tables). I have had to Disable the Timeout(set it to 0), because some SQL Statements can take several mins to run.
The problem comes when I want to stop the queries. Right now I have to wait till that current SQL Statement finished (like I said it could take several mins).

Below is code that works, from my existing knowledge (To help others):

MySqlConnectionStringBuilder ConnectionString = new MySqlConnectionStringBuilder();
ConnectionString.Server = ServerName;  // ServerName is a user defined string
ConnectionString.Database = DatabaseName; // DatabaseName is a user defined string
ConnectionString.UserID = UserName; // UserName is a user defined string
if (!Password.Equals(string.Empty)) // Password is a user defined string
{ ConnectionString.Password = Password; } // If Password string is not empty, then add it.
ConnectionString.AllowUserVariables = true; 

using (MySqlConnection connection = MySqlConnection(ConnectionString))
{
   try
   {
       connection.Open();
      DBTransaction Trans = connection.BeginTransaction();

       using (MySqlCommand Command = connection.CreateCommand())
       {
              foreach(String SQLCommandString in SQLCommands) // SQLCommands is user defined List<String>
              {
                   try
                   {
                          Command.CommandText = SQLCommandString; // SQLCommandString is a user defined string ex "UPDATE MyTable SET MyVar = 3 WHERE id = 3;"
                         NumOfRecordAffected = Command.ExecuteNonQuery();
                   }
                   catch (MySql.Data.MySqlClient.MySqlException ex)
                   {
                         Trans.RollBack();
                         // If code reaches here then there was a problem with the SQLCommandString executing.
                         throw ex;
                   }
                   catch (Exception ex)
                   {
                           // There was a problem other than with the SQLCommandString.
                           throw ex;
                   }
              }
       }
       Trans.Commit();
 }
役に立ちましたか?

解決

You can't do this in a single threaded application, because control won't return until a) the query has completed execution or b) an exception forces control to return.

Instead, you can start and execute all transactions in a worker thread and close the connection from the original thread if needed. Calling MySqlConnection.Close() will rollback any pending transactions.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top