如何在命令启动后更改sql超时

本文关键字:sql 超时 启动 命令 | 更新日期: 2023-09-27 18:08:24

问题:有没有一种方法可以在Command.ExecuteNonQuery()完成之前停止它,而不使用超时

我创建了一个多线程MySQL程序,用于存储和运行sql语句。允许一组事务同时运行(因为它们不修改相同的表(。我不得不禁用超时(将其设置为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();
 }

如何在命令启动后更改sql超时

您不能在单线程应用程序中执行此操作,因为在a(查询完成执行或b(异常迫使控件返回之前,控件不会返回。

相反,您可以在工作线程中启动和执行所有事务,并在需要时关闭来自原始线程的连接。调用MySqlConnection.Close()将回滚任何挂起的事务。