的问题:的
有没有办法在完成之前停止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();
}
答案 0 :(得分:1)
您不能在单线程应用程序中执行此操作,因为在a)查询已完成执行或b)异常强制控制返回之前,控件不会返回。
相反,您可以在工作线程中启动和执行所有事务,并在需要时关闭原始线程的连接。调用MySqlConnection.Close()
将回滚任何待处理的事务。