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
- It looks like this procedure works great on line
account1Name = r.GetValue(0).ToString();
. Perhaps you want to check the return valuer.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()
insteadExecuteReader()
.
+1
a source to share