1

I have the following method which is used to populate a DAO from the database. It performs 3 reads - one for the primary object, and 2 for some translations.

public bool read(string id, MySqlConnection c)
{
    MySqlCommand m = new MySqlCommand(readCommand);
    m.Parameters.Add(new MySqlParameter("@param1", id));
    m.Connection = c;
    MySqlDataReader r = m.ExecuteReader();
    r.Read();
    accountID = Convert.ToInt32(r.GetValue(0).ToString());
    ...
    comment = r.GetValue(8).ToString();
    r.Close();
    m = new MySqlCommand(getAccountName);
    m.Parameters.Add(new MySqlParameter("@param1", accountID));
    m.Connection = c;
    r = m.ExecuteReader();
    r.Read();
    account1Name = r.GetValue(0).ToString();
    r.Close();
    m = new MySqlCommand(getAccountName);
    m.Parameters.Add(new MySqlParameter("@param1", secondAccountID));
    m.Connection = c;
    r = m.ExecuteReader();
    r.Read();
    account2Name = r.GetValue(0).ToString();
    r.Close();
    return true;
}

On the line account2Name = r.GetValue(0).ToString(); I get the following error:

Invalid attempt to access a field before calling Read()

I don't understand what the problem is - the previous line calls read!

2 Answers 2

3

That seems to be working earlier in your code. Are you sure there is a value to read there (i.e. is your query returning 0 rows or null or something else that can't be converted to a string?)

Sign up to request clarification or add additional context in comments.

Comments

1
  1. Looks like that procedure works fine on the line account1Name = r.GetValue(0).ToString();. Maybe you want to check the return value of r.Read() to see if there are any rows first. The error could be interpreted as "Attempted to access a field without data"...
  2. It looks like you're trying to get a single value out of a query. You might want to look into the ExecuteScalar() method instead of ExecuteReader().

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.