1

By using this code I want to retrieve from the DB some rows from a table:

ID int
ParentID int?
IsVisible bool

MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection);
myConnection.Open();
MySqlDataReader myReader = myCommand.ExecuteReader();

try
{
  while(myReader.Read()) 
  {
    //here I want to retrieve the all returned data
  }
}
finally
{
  myReader.Close();
  myConnection.Close();
}

1 Answer 1

2

Something like

while(myReader.Read()) 
{
ID = AsInteger(myReader["ID"]).Value;
Parent = AsInteger(myReader["Parent"]);
IsVisble = AsBoolean(myReader["IsVisible"]);
}

Where As... are helper functions may be like

private static int? AsInteger(Object argValue)
{
   if ((argValue == null) || (argValue == DBNull.Value))
   {
     return null;
   }
   return Convert.ToInt(argValue);
}

etc

Whapping all the helper methods in the ubiquitious static helper class is usally goer, unless you rea doing all this in one class.

Watch for DBNull, it's not null. :(

And Blobs which are byte[] if they aren't DBNull. Haven't done it either but some of MySql's funny types like Date and Time might cause a furrowed brow, and enums come across as a string I seem to remember. What I remember is from an investigation some time ago whether to have MySQl as backend for one of our products as an alternative to sql server.

You can also access the columns of the result with an index

e.g. myReader[0].

Ther are loads of methods on the class, GetValues returns an array of object based on the current row.

This might come in handy as well

if (myReader.Read())
{
   StringBuilder sb = new StringBuilder(myReader.FieldCount);
   for(int i = 0; i<myReader.FieldCount; i++)
   {
      sb.AppendLine(myReader.GetName(i);
   }
   Console.Write(sb.ToString());   
}
Sign up to request clarification or add additional context in comments.

4 Comments

hmm if I try to get myReader["ParentID"] then I get an exception Could not find specified column in results: ParentID even if I want to get the select * from Table. Of course that column exist in that table
No way to say from here, but something funny is going on if you can't. You can also access the results as an array, as in myReader[0], so you could do a foreach and list them out and see what's what.
if I want to run the loop foreach (var item in myReader){} it is invoked 4 times (it's correct) but the compiler doesn't enter inside that loop
Hold on I'll eiut my answer a bit

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.