2012-02-15 17 views
1

我有这样的代码和它只有返回第一串[0]和他们的休息话说指数误差超出这意味着只有1行越来越拉到阵列,但我不知道为什么!为什么ExecuteReader只给我一行数据?

MySqlConnection connection = new MySqlConnection(MyConString); 
MySqlCommand command = new MySqlCommand("SELECT email_address FROM account_info", connection); 
MySqlDataReader reader; 

try 
{ 

    connection.Open(); 
    reader = command.ExecuteReader(); 
    if (reader.HasRows) 
    { 
     while (reader.Read()) 
     { 
      textBox1.Text = reader[0].ToString(); 

      textBox2.Text = reader[0].ToString(); 

      textBox3.Text = reader[0].ToString(); 
     } 


     reader.Close(); 
    } 

回答

2

由于您只拨打reader.Read()一次,您只获取一行。每次您拨打Read()时,阅读器前进到下一行并返回true;或者,当阅读器前进到最后一行时,它返回false。

索引器从附加的列中返回数据,并且在查询中只有一列;这就是为什么索引1和2失败。

编辑:

如果你是通过阅读器试图循环,你需要把你的三个文本框在那里他们可以通过被环以及结构。简单,但不够灵活,但正确的:

if (reader.HasRows) 
{ 
    reader.Read() 
    textBox1.Text = reader[0].ToString(); 
    reader.Read() 
    textBox2.Text = reader[0].ToString(); 
    reader.Read() 
    textBox3.Text = reader[0].ToString(); 
    reader.Close(); 
} 

更加灵活:

List<TextBox> boxes = new List<TextBox> { textBox1, textBox2, textBox3 }; 
for (int index = 0; index < boxes.Count; index++) 
{ 
    if (!reader.Read()) 
    { 
     break; // in case there are fewer rows than text boxes 
    } 
    boxes[index] = reader[0].ToString(); 
}  
+0

所以我把它在每个文本框中之间? – 2012-02-15 22:16:08

+0

@DevinPrejean这是做到这一点的一种方法。通常,在一个循环中调用Read()。 (请注意,它让你知道当所有的行已经阅读返回boolean)。在这种情况下,由于您填写的控制一定的数量,就可以调用'阅读()'反复或把控制进一个集合,所以你可以使用循环。 – phoog 2012-02-15 22:20:18

+0

甚至跑步reader.read 3个不同时间没有工作...... – 2012-02-15 22:26:10

5

reader[0]从阅读器,而不是第一行访问的第一个字段。请查看MSDN的示例代码。

// Call Read before accessing data. 
while (reader.Read()) 
{ 
    Console.WriteLine(String.Format("{0}, {1}", 
      reader[0], reader[1])); 
} 

这写出每行的第一列和第二列。

此外,我不确定为什么你没有使用using声明,以及为什么你在finally块中调用ExecuteReader - 这些看起来都很奇怪。

+0

我使用Windows窗体而不是console.writeline如何看? – 2012-02-15 22:15:47

+0

您是否尝试显示未知数量的电子邮件地址,或仅显示前三个?如果只是前三个,只需使用for循环替换while循环即可。如果一个未知的数字,你需要一些数据网格,也许'DataGridView'来做到这一点。 – dsolimano 2012-02-15 22:20:06

+0

我只需要前3我想要一个for循环和aparently我不明白它需要在语法 – 2012-02-15 22:24:34

0

这里是我做什么,替换字符串EmailAddress的部分基础知识你需要什么:

 using (SqlConnection SQL_Conn01 = new SqlConnection(SQLSync)) 
     { 
      bool IsConnected = false; 
      try 
      { 
       SQL_Conn01.Open(); 
       IsConnected = true; 
      } 
      catch 
      { 
       // unable to connect 
      } 
      if (IsConnected) 
      { 

       SqlCommand GetSQL = new SqlCommand("SELECT email_address FROM account_info", SQL_Conn01); 

       using (SqlDataReader Reader = GetSQL.ExecuteReader()) 
       { 
        while (Reader.Read()) 
        { 
         string EmailAddress = Reader.GetString(0).TrimEnd(); 
        } 
       } 
       GetSQL.Dispose(); 
      } 
     } 
相关问题