题
我有这个代码,它仅返回第一个字符串[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();
}
解决方案
您只会得到一排,因为您只是打电话 reader.Read()
一次。每次打电话 Read()
, ,读者进入下一行并返回真实;或者,当读者超越最后一行时,它会返回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();
}
其他提示
reader[0]
从读者而不是第一行访问第一个字段。从中查看示例代码 MSDN.
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
这写下了每一行的第一列和第二列。
另外,我不确定为什么您不使用 using
声明,以及为什么打电话 ExecuteReader
在里面 finally
块 - 它们看起来都很奇怪。
这是我所做工作的基础知识,请用您需要的任何内容替换字符串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();
}
}
不隶属于 StackOverflow