Wrong attempt to access the field before calling the read () function

I searched for a good couple of hours looking for a solution to this problem. I am trying to get information from my database using the following code with the correct queries. I know that these queries work because I tested them in MySQL workbench. I keep getting the error:

Invalid attempt to access a field before calling read ()

As you will see, I call read (), and my research only figured out that you are not using the correct database, and I also confirmed its correctness. Any ideas as to why I am getting this error? Thank you in advance.

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; } 
+4
source share
1 answer

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: What you are actually doing is getting a scalar, and you can use ExecuteScalar ()

 return (myCommand.ExecuteScalar() ?? string.Empty).ToString(); //also rename your method appropriately 
+7
source

All Articles