c# mysql query with select distinct column

1.1k views Asked by At

I am trying to put the DISTINCT rows (which is a small string) in a string variable targeting a textbox, but it only returns some of the rows with different content in the column. I used similar code but targeting a datagridview and works ok. I tried different approaches, where am I wrong?

stConsulta = "SELECT distinct symbol from ticks";
MySqlCommand MyCmd = new MySqlCommand(stConsulta,cnn);
MyCmd.Connection = cnn;
MyCmd.CommandText = stConsulta;
MySqlDataReader myreader = MyCmd.ExecuteReader();
if (myreader.HasRows)
{
    while (myreader.Read())
    {
        myreader.Read();
        stSymbols = stSymbols +  myreader.GetString("symbol") + " ";
    }
}                        
cnn.Close();
textBox1.Text = stSymbols;
3

There are 3 answers

1
Grant Winney On BEST ANSWER

Do not call myReader.Read() twice, for starters. You're skipping every other row.

You indicated there aren't many rows, but you may also want to use a StringBuilder for efficiency.

...
var stSymbols = new StringBuilder();

while (myreader.Read())
    stSymbols.Append(myreader.GetString("symbol") + " ");

...
textBox1.Text = stSymbols.ToString();
0
Kirk On

Just ignore this line inside the loop

myreader.Read();

when you use this in the condition of while(myreader.Read()) it starts reading it. so don't call it again in side the loop. that's what your mistake is.

if (myreader.HasRows)
{
    while (myreader.Read())
    {
        stSymbols = stSymbols +  myreader["symbol"].ToString() + " ";
    }
} 

And you're good to go

3
shujaat siddiqui On
if (myreader.HasRows)
{
    while (myreader.Read())
    {
        stSymbols = stSymbols +  myreader["symbol"].ToString() + " ";
    }
}