我得到了一个错误:"ExecuteReader需要一个打开的连接“,而且我知道修复方法是添加一个connection.Open() / connection.Close()。我关于这个错误的问题更多的是让我理解在引擎盖下到底发生了什么。
我目前正在使用" using“语句,我希望它能为我打开和关闭/释放连接。因此,我想我不明白为什么它不能像预期的那样工作,我需要自己显式地编码connection.Open() / connection.Close()来解决这个问题。我做了一些研究,发现人们经历了类似的问题,因为他们使用的是静态连接。在我的例子中,我正在创建一个连接的新实例.因此,它困扰着我,希望能找到真相,而不是仅仅修复它,然后继续前进。提前谢谢你。
以下是代码:
try
{
using (SqlConnection connection = new SqlConnection(myConnStr))
using (SqlCommand command = new SqlCommand("mySPname", connection))
{
command.CommandType = CommandType.StoredProcedure;
//add some parameters
SqlParameter retParam = command.Parameters.Add("@RetVal", SqlDbType.VarChar);
retParam.Direction = ParameterDirection.ReturnValue;
/////////////////////////////////////////////////
// fix - add this line of code: connection.Open();
/////////////////////////////////////////////////
using(SqlDataReader dr = command.ExecuteReader())
{
int success = (int)retParam.Value;
// manually close the connection here if manually open it. Code: connection.Close();
return Convert.ToBoolean(success);
}
}
}
catch (Exception ex)
{
throw;
}发布于 2015-05-01 15:54:04
使用不打开任何连接,它只在调用结束后处理任何分配的内存。
发布于 2015-05-01 15:56:09
对于SqlConnection,您必须在using块中显式地打开它,只是不需要关闭它。
我还注意到,您在使用SqlConnection时缺少了一组括号{}。也许这就是问题所在?应该是这样的:
try
{
using (SqlConnection connection = new SqlConnection(myConnStr))
{
connection.Open();
using (SqlCommand command = new SqlCommand("InsertProcessedPnLFile", connection))
{
command.CommandType = CommandType.StoredProcedure;
//add some parameters
SqlParameter retParam = command.Parameters.Add("@RetVal", SqlDbType.VarChar);
retParam.Direction = ParameterDirection.ReturnValue;
/////////////////////////////////////////////////
// fix - add this line of code: connection.Open();
/////////////////////////////////////////////////
using(SqlDataReader dr = command.ExecuteReader())
{
int success = (int)retParam.Value;
// manually close the connection here if manually open it. Code: connection.Close();
return Convert.ToBoolean(success);
}
}
}
}https://stackoverflow.com/questions/29990282
复制相似问题