gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:46:15 26 4
gpt4 key购买 nike

我有下面带有 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com