2012-08-03 46 views
0

你好是有使用兩個SqlDataReader對象在同一時間的方法嗎?C#同時使用2個sqldatareader?

我正在編寫一個程序

因爲我在代碼

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

相同

樣品使用2名讀者,我得到的錯誤和給我的錯誤

已經有一個用此命令, 必須先關閉相關聯的打開的DataReader。

+0

非常有用的答案 – ThElitEyeS 2012-08-03 20:53:20

回答

6

該錯誤消息是誤導性的。您必須在連接字符串中MultipleActiveResultSets=True一套能夠用兩個不同的讀者發送兩個單獨的命令。

+0

謝謝了我的答案:) – ThElitEyeS 2012-08-03 20:52:42

4

當您使用一種叫做多活動結果集,或MARS這是可能的。檢查出this helpful article,詳細說明所有可能的陷阱。

0

聲明DataReader的那些塊中的public partial class Form1 : Form例子:

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

1.Just添加MultipleActiveResultSets =真到您的連接字符串:

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