1

我有这段代码,它只返回第一个字符串 [0],其余的错误说索引不在数组中,这意味着只有 1 行被拉出但我不知道为什么!!!

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

3 回答 3

5

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

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

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

另外,我不确定您为什么不使用using语句,以及为什么要ExecuteReaderfinally块中调用-它们看起来都很奇怪。

于 2012-02-15T22:11:17.873 回答
2

你只得到一排,因为你只打电话reader.Read()一次。每次调用Read()时,reader 都会前进到下一行并返回 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();
}    
于 2012-02-15T22:10:29.027 回答
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();
            }
        }
于 2012-02-15T23:43:47.710 回答