Mysql query result access by field name

Steven Schveighoffer schveiguy at
Mon May 21 14:16:12 UTC 2018

On 5/20/18 12:08 PM, ipkwena wrote:
> I have started learning D and I am enjoying it so far.
> How does one access the columns fields in a Mysql query results by the 
> column name. Currently I have to use the method as shown in a couple of 
> example by indexing array values (f being a struct variable):
> Data f;
> = to!string(allrows[0][0]);
> f.surname = to!string(allrows[0][1]);
> f.title  = to!string(allrows[0][2]);
> I am using the mysql-native package or DB connectivity.

This is one of the weak spots of mysql-native -- the Row object has no 
knowledge of the column names, so you have to "know" the order of the 
columns you got from the server.

So what you can do is:

1. Use ResultRange instead of the Row interface. This provides a couple 
of ways to use column names, .asAA to get all the data in a nice AA 
format (they are still variants), .colNames to get the list of column 
names ordered by the row fields, or .colNameIndicies which gives you an 
AA of names to indices. Note that the AA generating versions will 
allocate a lot of throw-away data.

2. Write a complicated serialization library like I did :) In this case, 
I'm turning my ResultRange from a range of Rows to a range of the data 
type I want, all serialized by column name instead of index. 
Unfortunately, this is not open source so I can't share it.

At some point, I want to fix this part of mysql-native. I'm a bit 
annoyed that we have to do Variants instead of writing directly to the 
data type we are going to use anyway.


More information about the Digitalmars-d-learn mailing list