首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ExecuteReader需要打开连接

ExecuteReader需要打开连接
EN

Stack Overflow用户
提问于 2015-05-01 15:51:22
回答 2查看 156关注 0票数 1

我得到了一个错误:"ExecuteReader需要一个打开的连接“,而且我知道修复方法是添加一个connection.Open() / connection.Close()。我关于这个错误的问题更多的是让我理解在引擎盖下到底发生了什么。

我目前正在使用" using“语句,我希望它能为我打开和关闭/释放连接。因此,我想我不明白为什么它不能像预期的那样工作,我需要自己显式地编码connection.Open() / connection.Close()来解决这个问题。我做了一些研究,发现人们经历了类似的问题,因为他们使用的是静态连接。在我的例子中,我正在创建一个连接的新实例.因此,它困扰着我,希望能找到真相,而不是仅仅修复它,然后继续前进。提前谢谢你。

以下是代码:

代码语言:javascript
复制
        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;            
        }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-05-01 15:54:04

使用不打开任何连接,它只在调用结束后处理任何分配的内存。

票数 2
EN

Stack Overflow用户

发布于 2015-05-01 15:56:09

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

我还注意到,您在使用SqlConnection时缺少了一组括号{}。也许这就是问题所在?应该是这样的:

代码语言:javascript
复制
 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);
            }
        }
        }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29990282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档