Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid attempt to access field before calling read()

Tags:

c#

database

mysql

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 queries. I know these queries work because I have tested them in MySQL workbench. I keep getting the error:

Invalid attempt to access field before calling read()

As you will see, I do call read(), and my research has only come up with not using the correct database, which I have also verified to be correct already. Any ideas as to why I am receiving this error? Thanks in advance for the help.

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();

    statement = myReader.GetString(0);
    myReader.Close();

    return statement;
}
like image 372
SubxZero Avatar asked Jun 18 '12 19:06

SubxZero


1 Answers

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
like image 159
csauve Avatar answered Oct 16 '22 08:10

csauve