Reputation: 653
I am having a problem is getting a value from mysql using c#. The connection string is right, but it throws the following error: Invalid attempt to access a field before calling Read()
Can anyone tell me the problem which occurs in the code below
string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection = new MySqlConnection(strConnection);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader reader;
command.CommandText = "SELECT application_domain_name FROM `test`.`application_domains` WHERE idapplication_domains = " + reference;
connection.Open();
reader = command.ExecuteReader();
lblApplicationDomain.Text = reader.GetString(0);
connection.Close();
Upvotes: 0
Views: 1835
Reputation: 6275
You must call reader.Read() before accessing the results. Before you do that, the reader 'cursor' will be placed before the first element. Placing the cursor before the first element will make the behavior consistent even if the result set is empty.
Upvotes: 2
Reputation: 41236
You need to call reader.Read()
at least once. Like a normal SqlDataReader, the pattern is like so:
while(reader.Read())
{
.. Do Stuff
}
while(sqlDataReader.MoveNext())
{
.. Do Stuff
}
Upvotes: 0