c# - 错误 : ExecuteReader requires an open and available Connection. 连接的当前状态为打开

标签 c# asp.net-mvc-4

我有下面带有 DataHelperClass 的 mvc 4 网站来执行查询。我的问题有时是,网站以异常为标题。我使用 block 来处理 SqlCommand 和 SqlDataAdapter 但没有成功。

请帮助我,对不起我的英语。

        try
        {
            if (_conn.State == ConnectionState.Closed)
                _conn.Open();

            using (SqlCommand sqlCommand = new SqlCommand(query, _conn))
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;

                if (parameters != null)
                    sqlCommand.Parameters.AddRange(parameters);

                //// check transaction is exist
                if (_trans != null)
                    sqlCommand.Transaction = _trans;

                DataTable dt = new DataTable();
                using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
                {
                    sqlDataAdapter.Fill(dt);
                }

                return dt;
            }
        }
        finally
        {
            //// close connection automatically if transaction is not exist
            if (_trans == null) { _conn.Close(); }
        }

最佳答案

可能是你的连接没有真正打开造成的,因为调用这段代码时:

if (_conn.State == ConnectionState.Closed)
      _conn.Open();

连接状态可以是:Broken,或ConnectingFetching(查看全部enum list)。

如果您尝试在多个线程之间共享您的连接,则可能会发生这种情况。我认为每次调用此方法时都需要创建一个新连接。您可以找到许多如何操作的示例,包括 MSDN .

编辑:

这样的问题有很好的答案:ExecuteReader requires an open and available Connection. The connection's current state is Connecting

但是,如果您真的非常需要它,请尝试通过使用 lock 来防止对两个或多个线程使用相同的连接(实际上这是错误的,请参见上面的链接):

lock(_conn)
{
    DataTable dt = new DataTable();
    using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
    {
        sqlDataAdapter.Fill(dt);
    }
}

关于c# - 错误 : ExecuteReader requires an open and available Connection. 连接的当前状态为打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20673695/

相关文章:

C# 设置 Outlook 默认签名

c# - 如何防止 Log4Net 截断异常?

c# - 添加简单的 TagHelper 会导致此错误 : "RenderBody has not been called for the page "

c# - ASP.NET MVC - 显示一个项目列表,每个项目都有一个项目列表

asp.net-mvc-3 - 我可以在mvc3中将AdditionalMetadata与编辑器模板一起使用吗?

c# - 处理 ASP.NET MVC 时出错

c# - 在 ASP.NET MVC 中填充 DropDownList

c# - 使用 MVC Razor View 在表中插入多行

ASP.NET MVC 如何禁用自动缓存选项?

C#随机函数返回相同的值