Using MySQL Data Reader

Kevin Rodriguez picture Kevin Rodriguez · Apr 16, 2015 · Viewed 26k times · Source

I'm not familiar with using Data Reader, i need help with the following code, i want to retrieve a single data from the database.

MySqlDataAdapter data = new MySqlDataAdapter(cmd);
                    conn.Open();
                    DataTable dt = new DataTable();
                    data.Fill(dt);
                    gridView1.DataSource = dt;

                    int retrievedValue = 0;
                    using (MySqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            if ((int)reader["order_status"] == 0)
                            {
                                retrievedValue = (int)reader.GetValue(0);

                                    GridView View2 = sender as GridView;
                                    e.Appearance.BackColor = Color.Green;
                                    e.Appearance.BackColor2 = Color.ForestGreen;
                            }
                        }
                    }

Answer

Soner Gönül picture Soner Gönül · Apr 16, 2015

reader["order_status"] returns object, since you told it is an already integer, you need to cast it to int first.

You need to use == operator as well since it is a equality operator. = operator is an assignment operator.

if ((int)reader["order_status"] == 0)

Or you can use GetInt32 method with it's zero-based column number. Let's say it's the first column that your query returns, you can use it like;

if(reader.GetInt32(0) == 0)

By the way, if you wanna get only single value, I strongly suspect you may wanna use ExecuteScalar method since it get's the first column of the first row. Then you can structure your query as SELECT order_status FROM ... etc..