ExecuteReader 需要打开连接

ExecuteReader requires an open connection

我收到错误:"ExecuteReader requires an open connection",我知道解决方法是添加 connection.Open() / connection.Close()。我关于此错误的问题更多的是让我准确了解引擎盖下发生的事情。

我目前正在使用我希望它打开的 "USING" 语句和 close/dispose 连接。所以我想我不明白为什么它没有按预期工作,我需要自己明确编码 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;            
        }

Using 不会打开任何连接,它只会在调用 End Using 后处理所有分配的内存。

对于 SqlConnection,您必须在 using 块中显式打开它,但您不需要关闭它。

我还注意到您在 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);
            }
        }
        }
    }