Reputation: 780
In the following code for retrieving data via a SQL query from the db, is there a way I can replace row[0] with fieldname. I am only enclosing the relevant part of the code
MYSQL_RES *resptr;
MYSQL_ROW row;
while ( ( row = mysql_fetch_row(resptr)) != NULL )
{
for (int i=0;i<8;i++)
string key = row[0];
}
row[0] is the trans_date column. the code works fine as it is right now, but is there a way to assign key by using the fieldname vs. having to remember all the field numbers. thanks!
Upvotes: 1
Views: 1329
Reputation: 42343
MySQL++ solves this problem. You can say things like:
string key = row["key"];
or by use of its SSQLS feature, this:
MyTableStructure foo = result[i];
cout << "The key is " << foo.key << endl;
Upvotes: 0
Reputation: 24078
You can retrieve field names by doing
field = mysql_fetch_field(resptr);
std::cout << field->name;
(Put in a while loop to loop through all field)
But you can't call row[fieldName]
. What you can do though is define variables to map column names and numbers
int id = 0;
int trans_date = 1;
// Code happening here
std::cout << row[id] << " " << row[trans_date];
UPDATE: You could always do something like this (using STL's map):
map<string, int> columns;
int i = 0;
while(field = mysql_fetch_field(resptr)){
columns.insert(pair<string,int>(field->name, i++));
}
And then use row[columns["name"]];
.
Upvotes: 2