Why is ExecuteReader only giving me 1 row of data back?
-
29-04-2021 - |
题
I have this code and its only returning the first string [0] and errors on the rest of them saying the index is out of the array which means only 1 row is getting pulled BUT I DON'T KNOW WHY!!!
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();
}
解决方案
You're only getting one row because you're only calling reader.Read()
once. Each time you call Read()
, the reader advances to the next row and returns true; or, when the reader advances past the last row, it returns false.
The indexer returns data from additional columns, and you have only one column in your query; that's why index 1 and 2 are failing.
EDIT:
IF you're trying to loop through the reader, you need to put your three textboxes in a structure where they can be looped through as well. Simpler, but less flexible, but correct:
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();
}
more flexible:
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]
accesses the first field from the reader, not the first row. Check out the sample code from MSDN.
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
This writes out the first and second columns of each row.
Also, I'm not really sure why you're not using a using
statement, and why you're calling ExecuteReader
in the finally
block - those both look odd.
Here's the basics of what I do, replace the string EmailAddress part with whatever you need:
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();
}
}