我有mvc 4网站,下面有DataHelperClass来执行查询.我的问题有时候,网站通过例外作为标题.我用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(); }
}
Run Code Online (Sandbox Code Playgroud)
可能导致您的连接未真正打开,因为调用此代码时:
if (_conn.State == ConnectionState.Closed)
_conn.Open();
Run Code Online (Sandbox Code Playgroud)
连接状态可以是:Broken,或Connecting或Fetching(参见所有枚举列表).
如果您尝试在多个线程之间共享连接,则可能会发生这种情况.我认为每次调用此方法时都需要创建一个新连接.您可以找到许多示例,包括MSDN.
编辑:
这个问题有一个很好的答案:ExecuteReader需要一个开放且可用的连接.连接的当前状态为"正在连接"
但是如果你确实需要它,请尝试通过使用防止使用与两个或多个线程相同的连接lock(实际上是错误的,请参阅上面的链接):
lock(_conn)
{
DataTable dt = new DataTable();
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
{
sqlDataAdapter.Fill(dt);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27817 次 |
| 最近记录: |