【问题标题】:Mysql/C# error: There is already an open DataReader associated with this Connection which must be closed firstMysql/C# 错误:已经有一个打开的 DataReader 与此 Connection 关联,必须先关闭
【发布时间】:2011-07-25 06:20:31
【问题描述】:

我有一段代码可以执行 mysql 命令,但有时它会抛出异常

已经有一个打开的 DataReader 与此 Connection 关联,必须先关闭它

何时抛出异常是不可预知的,有时我的程序可以正常工作超过 15 分钟,但随后会崩溃。我在网上寻找答案,但我什么也没找到。 这是我的代码:

 public static List<string> DoCommand(string commandLine, string myConString) {
             MySqlCommand command = new MySqlCommand(commandLine);
            List<string> tables = new List<string>();
            try {
                using (MySqlConnection mySqlConnection = new MySqlConnection(myConString)) {
                    mySqlConnection.Open();
                    command.Connection = mySqlConnection;
                    command.BeginExecuteReader();
                    using (MySqlDataReader SqlDR = command.ExecuteReader()) {
                        while (SqlDR.Read()) {  //Async reading, wait untill reading is done
                            tables.Add(SqlDR.GetString(0));
                        }
                        //SqlDR.Close();
                        //SqlDR.Dispose();
                    }
                    //mySqlConnection.Close();
                    //mySqlConnection.Dispose();
                }
            } catch (Exception exp) { } finally {
                command.Connection = null;
            }
            //System.Threading.Thread.Sleep(50);     //Give connection time to flush
            return tables;
        }

有一些解决方案在评论中不起作用。 这是连接到 mysql 的唯一代码,所以我确信所有连接都已关闭

【问题讨论】:

    标签: c# mysql exception-handling datareader


    【解决方案1】:

    如果您上面的代码是您想要的,则不需要此行:

      command.BeginExecuteReader(); 
    

    SqlCommand.BeginExecuteReader 方法:

    启动异步执行 Transact-SQL 语句或 描述的存储过程 此 SqlCommand,并检索一个或 来自服务器的更多结果集

    【讨论】:

      【解决方案2】:

      替换

      using (MySqlDataReader SqlDR = command.ExecuteReader())
      

      using (MySqlDataReader SqlDR = command.EndExecuteReader()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-18
        • 1970-01-01
        • 2019-01-17
        • 2020-09-25
        • 2011-12-26
        • 1970-01-01
        相关资源
        最近更新 更多