C # MySQL parameterized parameter issue

I have the following method which is used to populate a DAO from a database. It does 3 readings - one for the main 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;
}

      

The account2Name = r.GetValue(0).ToString();

following error appears on the line :

Invalid attempt to access a field before calling Read()

      

I don't understand what the problem is: the previous lines are being read!

+1


a source to share


2 answers


This seems to work before in your code. Are you sure there is a value to read in there (i.e. your query returns 0 rows or zero or something else that cannot be converted to a string?)



+3


a source


  • It looks like this procedure works great on line account1Name = r.GetValue(0).ToString();

    . Perhaps you want to check the return value r.Read()

    to see if there are any rows in the first place. The error can be interpreted as "Attempting to access a field without data" ...
  • It looks like you are trying to get one value from a request. You might want to explore the method ExecuteScalar()

    instead ExecuteReader()

    .


+1


a source







All Articles