2011-06-01 36 views
0

我有一個問題是從MySQL使用C#獲取值。連接字符串是正確的,但它引發以下錯誤:無效的嘗試調用讀前訪問一個字段()C#ASP.NET簡單選擇問題

誰能告訴我發生在下面的代碼

  string strConnection = ConfigurationSettings.AppSettings["ConnectionString"]; 
      MySqlConnection connection = new MySqlConnection(strConnection); 
      MySqlCommand command = connection.CreateCommand(); 
      MySqlDataReader reader; 
      command.CommandText = "SELECT application_domain_name FROM `test`.`application_domains` WHERE idapplication_domains = " + reference; 
      connection.Open(); 
      reader = command.ExecuteReader(); 

      lblApplicationDomain.Text = reader.GetString(0); 

      connection.Close(); 
+2

參見:[一個媽媽的漏洞(http://xkcd.com/327/) – 2011-06-01 18:46:32

回答

2

問題必須調用reader.Read()訪問結果之前。 在這之前,閱讀器'光標'將放置在第一個元素之前。即使結果集爲空,將光標放在第一個元素之前也會使行爲保持一致。

0

您需要至少撥打reader.Read()一次。像正常SqlDataReader的,該圖案是像這樣:

while(reader.Read()) 
{ 
    .. Do Stuff 
} 

while(sqlDataReader.MoveNext()) 
{ 
    .. Do Stuff 
}