0

Right now, I'm using a MySqlDataReader to read the result from a query and using reader.GetInt(), reader.GetString(), etc. to get the value of each cell like so:

var cmd = new MySqlCommand(query, conn);
var reader = cmd.ExecuteReader();
while(reader.Read()) {
   myfirstvalue = reader.GetInt32(0);
   mysecondvalue = reader.GetString(1);
   mythirdvalue = reader.GetString(2);
   ...
}

This works and all, but it kind of grabs the values blindly. You might get an unexpected value if the order of the results gets changed.

Can I retrieve the returned results by column name? Back in my PHP days, you could get an array and access the values like $results['mycolumn']. Is this possible in C#?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
bwoogie
  • 4,339
  • 12
  • 39
  • 72
  • sure http://i.imgur.com/RKVo4uz.jpg – Drew Oct 05 '16 at 19:21
  • You're looking for [GetOrdinal](https://dev.mysql.com/doc/dev/connector-net/html/M_MySql_Data_MySqlClient_MySqlDataReader_GetOrdinal.htm)...but the _"order of the results gets changed"_ should really not be an issue if you are handling queries safely. Also, keep in mind if you're looping through a lot of results, you may want to just get the ordinals once, not on every field access of every row. – Uueerdo Oct 05 '16 at 19:21
  • Yes. The datareader order will always be in the order of the SELECT statement (eg SELECT col2, col3, col5 FROM mytable will produce reader[0] = col2, reader[1] = col3, reader[2] = col5). But you can also access as reader["col2"] UPDATE - was thinking SQL... use GetOrdinal – Shannon Holsinger Oct 05 '16 at 19:22
  • Possible duplicate of [How to read specific column and cell in mysql in c#?](http://stackoverflow.com/questions/15904333/how-to-read-specific-column-and-cell-in-mysql-in-c) – Eugene Pawlik Oct 05 '16 at 19:23
  • The MySqlDataReader has these overloads of the GetXXXX methods that accepts a column name. Just try. – Steve Oct 05 '16 at 19:29
  • Thanks! I overlooked the override allowing you to get by the column name. – bwoogie Oct 05 '16 at 19:31
  • @bwoogie you can use reader["CompanyName"] – Zulqarnain Jalil Oct 05 '16 at 20:13
  • Maybe this will help: https://stackoverflow.com/questions/25946108/c-sharp-mysql-get-value-from-column-if-status-is-a – Momoro Feb 09 '20 at 09:11

0 Answers0