问:
有没有办法阻止Command.ExecuteNonQuery()
在它完成之前停止它,而不使用超时?
我创建了一个存储和运行 sql 语句的多线程 MySQL 程序。允许一组事务同时运行(因为它们不修改同一张表)。我不得不禁用超时(将其设置为 0),因为某些 SQL 语句可能需要几分钟才能运行。
当我想停止查询时,问题就来了。现在我必须等到当前的 SQL 语句完成(就像我说的可能需要几分钟)。
根据我现有的知识,以下是有效的代码(帮助他人):
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();
}