无效尝试接入领域调用read()之前 [英] Invalid attempt to access field before calling read()
问题描述
我已经寻找一个好几个小时了,寻找一个解决这个问题。我试图让使用下面用正确的查询代码从我的数据库信息。我知道这些查询工作,因为我已经在MySQL的工作台进行了测试。我不断收到错误:
无效的尝试调用read()
块引用>之前访问场
正如你所看到的,我不调用read(),而我的研究才想出没有使用正确的数据库,我也证实是正确的了。任何想法,为什么我收到这个错误?在此先感谢您的帮助。
公共静态字符串的ExecuteSelect(查询字符串)
{
//示例查询是:SELECT ENTITY_ID FROM catalog_product_flat_1 WHERE SKU ='itemSku';
字符串声明=;
的MySqlCommand myCommand =新的MySqlCommand(查询,_conn);
了MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
myReader.Read();
语句= myReader.GetString(0);
myReader.Close();
return语句;
}
解决方案不知道这是你的情况的问题,但您应经常检查阅读()的结果。例如:
如果(myReader.Read())
{
语句= myReader.GetString(0) ;
}
修改同时你实际上是在做什么检索标量,因此你可以使用的ExecuteScalar()
收益率(myCommand.ExecuteScalar()??的String.Empty)的ToString();
//也重新命名你的方法正确
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; }
解决方案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
这篇关于无效尝试接入领域调用read()之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!