Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Using 2 sqldatareader at same time?

Tags:

c#

sql

Hello is there a way to use two sqldatareader at same time ?

i was coding a program

and i got error because i use 2 readers at same

Sample of code

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();
}

and its gave me that error

There is already an open DataReader associated with this Command which must be closed first.

like image 495
ThElitEyeS Avatar asked Aug 03 '12 20:08

ThElitEyeS


3 Answers

The error message is misleading. You must have MultipleActiveResultSets=True set in your connection string to be able to send two seperate commands with two different readers.

like image 181
Mithrandir Avatar answered Oct 11 '22 15:10

Mithrandir


It is possible when you use something called Multiple Active Result Sets, or MARS. Check out this helpful article that details all possible pitfalls.

like image 39
Nikola Anusev Avatar answered Oct 11 '22 14:10

Nikola Anusev


You'll have to enable Multiple Active Recordsets (MARS) on your connection.

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

like image 31
Serg Rogovtsev Avatar answered Oct 11 '22 15:10

Serg Rogovtsev