Invalid attempt to access field before calling read()

前端 未结 2 1786
生来不讨喜
生来不讨喜 2021-01-19 01:18

I have searched for a good couple hours now, looking for a solution to this problem. I am trying to get information from my database using the code below with the correct qu

相关标签:
2条回答
  • 2021-01-19 01:28

    Not sure if this is the problem in your case, but you should always check the result of Read(). eg

    if (myReader.Read())
    {
      statement = myReader.GetString(0);
    }
    

    Edit: Also what you are actually doing is retrieving a scalar, and as such you could use ExecuteScalar()

    return (myCommand.ExecuteScalar() ?? string.Empty).ToString();
    //also rename your method appropriately
    
    0 讨论(0)
  • 2021-01-19 01:31

    I have just walked away from a similar issue as yours.My solution was to use a

    if (!myReader.HasRows)
                    {
    
                    }
    

    just before walking through the dataset.

    while(myRead.Read()
    {
     //read tuples
    }
    

    This would mean for your code:

    public static string ExecuteSelect(string query)
    {
    //Example query is: SELECT entity_id FROM catalog_product_flat_1 WHERE 
    sku='itemSku';
    string statement = "";
    
    MySqlCommand myCommand = new MySqlCommand(query, _conn);
    
    MySqlDataReader myReader;
    myReader = myCommand.ExecuteReader();
    myReader.Read();
    if(!myReader.HasRows)
    {
     //set your statement variable to some generic value
     statement="abracadabra";
    }
    
    while(myReader.Read())
    {
    statement = myReader[0].ToString();
    }
    myReader.Close();
    
    return statement;
    }
    
    0 讨论(0)
提交回复
热议问题