Using MySQL Data Reader

前端 未结 2 598
青春惊慌失措
青春惊慌失措 2021-01-13 22: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 = ne         


        
相关标签:
2条回答
  • 2021-01-13 23:16

    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.

    0 讨论(0)
  • 2021-01-13 23:17

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

    0 讨论(0)
提交回复
热议问题