【问题标题】:Having issue in connection string of already an open DataReader已经打开的 DataReader 的连接字符串出现问题
【发布时间】:2013-06-13 07:48:40
【问题描述】:

已经有一个打开的 DataReader 与此命令关联 必须先关闭。

当同一个人在不同系统上同时打开同一页面时,我会遇到这个问题。 我对此进行了很多搜索,但没有找到成功的解决方案。

我累了:

  1. 连接字符串中的MultipleActiveResultSets = true
  2. 增加连接等待时间
  3. 已验证所有连接均已关闭

只有在创建上述条件时才会出现此问题。请让我知道真正有效的解决方案

这是我正在使用的连接功能

public DataSet SelectDs(string str)
{
    DataSet ds = new DataSet();

    if (con.State == ConnectionState.Closed)
    {
        con.ConnectionString = ConStr;
        con.Open();
    }

    cmd.CommandText = str;
    cmd.Connection = con;
    cmd.CommandTimeout = 12000;
    adpt.SelectCommand = cmd;
    adpt.Fill(ds);

    con.Close();
    return ds;
}

【问题讨论】:

  • 如果您在出现问题的地方添加一些代码,您将有更多机会获得准确的答案。
  • 你能分享一些你得到这个错误的代码吗?
  • @AltafSami 这发生在我共享数据集连接功能的所有页面中
  • @Steve 这发生在我分享我的数据连接功能的所有页面中
  • @ArjunSharma 返回的记录数是多少??

标签: c# asp.net sql-server connection-string


【解决方案1】:

以这种方式使用全局连接对象是一种致命的罪过。它在 WinForms 应用程序中很糟糕(非常糟糕),但在 ASP.NET 中是致命的。 (正如你所发现的)

一次性对象(以及像连接这样昂贵的对象)的使用模式是

CREATE, OPEN, USE, CLOSE, DESTROY

Connection Pooling 机制的存在使这种模式的使用更容易。
相反,您试图与之抗衡并承担后果。

你的代码应该重写为

public DataSet SelectDs(string str)
{
    DataSet ds = new DataSet();

    using(SqlConnection con = new SqlConnection(constring))  // CREATE
    using(SqlCommand cmd = new SqlCommand(str, con))         // CREATE
    {
        con.Open();    // OPEN
        cmd.CommandTimeout = 12000;
        using(SqlAdapter adpt = new SqlAdapter(cmd))   // USE
             adpt.Fill(ds);

        return ds;
    }  // CLOSE & DESTROY 
}

【讨论】:

    【解决方案2】:

    如何在 Using 语句中放入

        using(SqlConnection connection = new SqlConnection("connection string"))
    {
    
    connection.Open();
    
    using(SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection))
    {
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            if (reader != null)
            {
                while (reader.Read())
                {
                    //do something
                }
            }
        } // reader closed and disposed up here
    
       } // command disposed here
    
     } //connection closed and disposed here
    

    【讨论】:

    • 我不能使用它,因为这需要我的连接类中的专业我正在使用公共对象
    • 那么你将面临艰难的日子
    【解决方案3】:

    在 finally 子句中使用 this

    if (readerObj.IsClosed == false)
    {
      readerObj.Close();
    }
    

    【讨论】:

      【解决方案4】:

      我认为您还应该在返回数据集之前处理您的命令对象。

      在 con.close() 之后尝试 cmd.Dispose()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-28
        相关资源
        最近更新 更多