1

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?

2
  • 1
    Should also point out that this method exposes you to SQL injection attacks. See little bobby tables about this. Commented Aug 15, 2011 at 3:15
  • hash is not an input from user Commented Aug 15, 2011 at 5:10

2 Answers 2

12

You are missing a reader.Read() call:

 MySqlDataReader reader = cmd.ExecuteReader();
 while(reader.Read())
 {
     String res = reader.GetString(0); 
     //...
 }
Sign up to request clarification or add additional context in comments.

Comments

4

Try:

string res;
using(MySqlDataReader reader = cmd.ExecuteReader())
{
    if(reader.Read())
        res = reader.GetString(0);
    else
        res = "not found";
}

If you change the SQL command to return a single value, for example:

"SELECT foo FROM info WHERE baa = '{0}' LIMIT 1"

then you can also use cmd.ExecuteScalar():

string res = cmd.ExecuteScalar().ToString();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.