C# 错误:ExecuteReader需要打开且可用的连接。连接';它的当前状态是开放的
我有MVC4网站和下面的DataHelperClass来执行查询。我的问题是,有时候,网站会被误认为是标题。我使用block来处理SqlCommand和SqlDataAdapter,但没有成功 请帮帮我,对不起我的英语C# 错误:ExecuteReader需要打开且可用的连接。连接';它的当前状态是开放的,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,我有MVC4网站和下面的DataHelperClass来执行查询。我的问题是,有时候,网站会被误认为是标题。我使用block来处理SqlCommand和SqlDataAdapter,但没有成功 请帮帮我,对不起我的英语 try { if (_conn.State == ConnectionState.Closed) _conn.Open(); using (SqlCommand sq
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();
连接状态可以是:断开
,或连接
或获取
(请参阅全部)
如果尝试在多个线程之间共享连接,则可能会发生这种情况。我认为每次调用此方法时都需要创建一个新连接。你可以找到很多例子,包括
编辑:
对于这样一个问题,有一个很好的答案:
但是如果您真的需要它,请尝试使用锁来防止对两个或多个线程使用相同的连接(实际上是错误的,请参见上面的链接):
最有可能的问题是示例中没有显示的static SqlConnection _conn
。我已经替换了if(_conn.State==ConnectionState.Closed)_conn.Open();使用if(_trans==null){u conn=new SqlConnection(Utility.Connect);_conn.Open()},但问题无法解决
lock(_conn)
{
DataTable dt = new DataTable();
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
{
sqlDataAdapter.Fill(dt);
}
}