Using MySQL Data Reader

不羁的心 提交于 2019-12-01 05:27:32

问题


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;
                            }
                        }
                    }

回答1:


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..




回答2:


Be sure to assign a variable before while (reader.Read()) otherwise it will and error. Then close the data reader once you are finished using it. Like so:

 using (MySqlDataReader reader = cmd.ExecuteReader())    
    {

    int retrievedValue = 0;

          while (reader.Read())
          {
                retrievedValue = (int)reader.GetValue(0);
                if (retrievedValue == 0)
                {

                    GridView View2 = sender as GridView;
                                    e.Appearance.BackColor = Color.Green;
                                    e.Appearance.BackColor2 = Color.ForestGreen;
                }
                else if (retrievedValue == 1)
                {

                    GridView View2 = sender as GridView;
                                    e.Appearance.BackColor = Color.Red;
                                    e.Appearance.BackColor2 = Color.ForestGreen;
                }
          }//and so on...
          reader.Close();
    }

I hope this is was you're looking for.



来源:https://stackoverflow.com/questions/29675721/using-mysql-data-reader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!