MultipleActiveResultSets已启用但无法正常工作

时间:2012-04-25 15:52:12

标签: c# sql

我启用了MARS并且仍然无法在一个连接中执行两个SqlDataReaders,我搜索了一个解决方案,默认情况下使用RegEdit启用MARS,因为找不到任何解决方案并仍然遇到错误:已经有一个与此命令关联的打开DataReader必须先关闭。

以下是代码:

public partial class student_Courses : System.Web.UI.Page
{
    string connectionString = "";
    string query1 = "";
    string query2 = "";
    string courseName = "";
    string chapterName = "";
    string chapterVideoName = "";
    string courseValue = "";
    SqlDataReader sr2 = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        query1 = "SELECT * FROM Courses";
        query2 = "SELECT * FROM Chapters WHERE value='" + courseValue + "'";
        connectionString = "Data Source=Prince-PC;" + 
                            "Initial Catalog=Elearning;" + 
                            "Integrated Security=True;"+ 
                            "MultipleActiveResultSets=True";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand command1 = new SqlCommand(query1, con);
        SqlCommand command2 = new SqlCommand(query2, con);
        if (con.State == ConnectionState.Closed)
            con.Open();

        using (SqlDataReader sr1 = command1.ExecuteReader())
        {
            while (sr1.Read())
            {
                courseName = sr1["name"].ToString();
                courseValue = sr1["value"].ToString();
                sr2 = command2.ExecuteReader();
                while (sr2.Read())
                {
                    chapterName = TextBox3.Text =  sr2["name"].ToString();
                    chapterVideoName = Label2.Text =  sr2["video_name"].ToString();
                }
            }
        }
        con.Close();
    }
}

1 个答案:

答案 0 :(得分:4)

您需要通过[{3}}

中的sr2语句处理using
// The following line of code requires
// a MARS-enabled connection.
productReader = productCmd.ExecuteReader();
using (productReader)
{
  while (productReader.Read())
  {
    Console.WriteLine("  " +
      productReader["Name"].ToString());
  }
}