C#同时使用2 sqldatareader?

时间:2012-08-03 20:44:57

标签: c# sql

你好,有没有办法同时使用两个sqldatareader?

我正在编写一个程序

我收到错误,因为我使用了2个读者

代码示例

SqlCommand LoadSilk = new SqlCommand("SELECT silk_own FROM SK_Silk WHERE JID = (SELECT JID FROM TB_User WHERE StrUserID = '"+ comboBox1.Text +"')", Connection);
SqlDataReader SilkReader = LoadSilk.ExecuteReader();
SqlCommand LoadCharacter = new SqlCommand("SELECT * FROM SRO_VT_SHARD.DBO._Char WHERE CharID IN (SELECT CharID FROM SRO_VT_SHARD.DBO._User WHERE UserJID = "+ JID +")", Connection);
SqlDataReader CharacterReader = LoadCharacter.ExecuteReader();

try
{
    SilkReader.Read();
    textBox5.Text = SilkReader[0].ToString();
    Silk = SilkReader[0].ToString();
    dataGridView1.Enabled = true;
    button2.Enabled = true;
    while (CharacterReader.Read()) {
        dataGridView1.Rows.Add(CharacterReader["CharID"].ToString(), CharacterReader["CharName16"].ToString(), CharacterReader["CurLevel"].ToString());
    }
    log(comboBox1.Text + " account data loaded");
}
catch (Exception ex) {
    log(ex.Message);
    MessageBox.Show("Error");
} finally {
    SilkReader.Close();
    CharacterReader.Close();
}

它给了我那个错误

  

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

5 个答案:

答案 0 :(得分:11)

错误消息具有误导性。您必须在连接字符串中设置MultipleActiveResultSets=True才能使用两个不同的读取器发送两个单独的命令。

答案 1 :(得分:5)

当您使用称为多个活动结果集或MARS的东西时,它是可能的。查看详细列出所有可能陷阱的this helpful article

答案 2 :(得分:3)

您必须在连接上启用多个活动记录集(MARS)。

http://msdn.microsoft.com/en-us/library/h32h3abf%28v=vs.80%29.aspx

答案 3 :(得分:1)

1.只需将MultipleActiveResultSets = True添加到您的连接字符串中:

private string _ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=yourdbpath\Database.mdf;Integrated Security=True;MultipleActiveResultSets=True;Connect Timeout=30";

答案 4 :(得分:0)

在块public partial class Form1 : Form中声明那些DataReader示例:

namespace GoodFood_1_
{
    public partial class Autentificare_client : Form
   {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\edi_b\Documents\visual studio 2013\Projects\GoodFood(1)\GoodFood(1)\GOOD_FOOD.mdf;
        Integrated Security=True;MultipleActiveResultSets=True");
        SqlConnection con2 = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\edi_b\documents\visual studio 2013\Projects\GoodFood(1)\GoodFood(1)\GOOD_FOOD.mdf;
        Integrated Security=True;MultipleActiveResultSets=True");

        SqlDataReader dr;
        SqlDataReader cc;

        public Autentificare_client()
        {
            InitializeComponent();
        }