【问题标题】:ASP.NET , SqlDataReader and SqlCommand (There is already an open DataReader associated with this Command which must be closed first)ASP.NET 、 SqlDataReader 和 SqlCommand (已经有一个打开的 DataReader 与此命令关联,必须先关闭)
【发布时间】:2016-06-30 02:15:12
【问题描述】:

我收到此错误:

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

我不知道问题出在哪里。它关闭了,但仍然说它是开放的。请帮忙!

第一个命令是获取所有在两个日期之间有假期的员工。

第二个命令我用它来按 ID 检索日期。

这是我的代码:

using (SqlConnection con = new SqlConnection(connection))
{
     con.Open();

     SqlCommand cmd = new SqlCommand(" SELECT distinct E.EmployeeId, E.FirstName FROM Employee E INNER JOIN Vacation V ON E.EmployeeId = V.EmployeeId " +
                                     " WHERE ((V.Dates >= @Start AND V.Dates <= @End) ) ", con);
     cmd.Parameters.AddWithValue("@Start", (Calendar1.SelectedDates[0]).Date.ToShortDateString());
     cmd.Parameters.AddWithValue("@End", (Calendar1.SelectedDates[Calendar1.SelectedDates.Count - 1]).Date.ToShortDateString());

    using (SqlDataReader dr = cmd.ExecuteReader())
    {
        while (dr.Read())
        {
             Response.Write((dr[1]).ToString() + "  "); // Check if retrieves employee name
             // Now by Id I want to get all dates belong to specific employee
             SqlCommand cmd2 = new SqlCommand("SELECT V.Dates FROM Vacation V " +
                                              " WHERE ((V.Dates >= @Start AND V.Dates <= @End) ) ", con);
             cmd2.Parameters.AddWithValue("@Start", (Calendar1.SelectedDates[0]).Date.ToShortDateString());
             cmd2.Parameters.AddWithValue("@End", (Calendar1.SelectedDates[Calendar1.SelectedDates.Count - 1]).Date.ToShortDateString());
             cmd2.Parameters.AddWithValue("@EmployeeId", Convert.ToInt32(dr[0]));                                    

             using (SqlDataReader dr2 = cmd2.ExecuteReader())
             {
                 while (dr2.Read())
                 {
                      Response.Write(Convert.ToDateTime(dr2[0]));
                 }
             }

             Response.Write("<br/>");
         } 

         GridView7.DataSource = cmd.ExecuteReader();
         GridView7.DataBind();
    }
    con.close();
}

【问题讨论】:

    标签: asp.net sql-server sqldatareader sqlcommand


    【解决方案1】:

    将此添加到您的连接字符串:

    MultipleActiveResultSets=True
    

    【讨论】:

    • 感谢您的回复,但您的意思是在我的 webconfig 中吗?它说不允许。
    • 是的,将其添加到连接字符串中。例如,
    • 我发现了问题。 gridView 在第一个 sqlconnection 内。当我把它移到一边时,每个 Think 都可以正常工作。再次感谢您。
    • 太棒了!祝你的项目好运。
    • 也许你能帮我解决这个问题?提前致谢:stackoverflow.com/questions/36018174/…
    猜你喜欢
    • 2011-08-29
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    相关资源
    最近更新 更多