Search code examples
c#mysql

MySqlCommand().ExecuteReader().GetString() does not work


I'm working with MySql in the C# programming language. I'm trying to get some data out of my database.

The fields are organized like this:

foo baa
38737 22222

I need to get the value of foo if my hash is equal to baa

I tried this:

My code(not working)
MySqlConnection con = new 
    MySqlConnection("Server=localhost;Database=test;Uid=user;Pwd=pass;");
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = string.Format("SELECT * FROM info WHERE baa = '{0}'", Hash);
cmd.Connection = con;
MySqlDataReader reader = cmd.ExecuteReader();
String res = reader.GetString(0); 

I'm getting the following error:

Invalid attempt to access a field before calling Read() 

Can someone point out my error?


Solution

  • You are missing a reader.Read() call:

     MySqlDataReader reader = cmd.ExecuteReader();
     while(reader.Read())
     {
         String res = reader.GetString(0); 
         //...
     }