MySQL C API - Access rows by column name
Is there a way to access the rows in a MySQL database using their column name?
For example, instead of using row[0]
for the first column, you would use something like row['autho开发者_Python百科rs']
. I want to program directly with the C API without any wrappers, and not in C++.
Thanks for your help!
C doesn't really have support for key value arrays like (I'm assuming your thinking of) PHP. The closest thing you could get would be to get an array of the column names, search it for the one you need, and use that index. For instance:
mysql_query(_MySQLConnection, query);
MYSQL_RES *result = mysql_store_result(_MySQLConnection);
unsigned int num_fields = mysql_num_fields(result);
MYSQL_ROW row;
MYSQL_FIELD *field;
unsigned int name_field;
char *field_name = "name";
char *headers[num_fields];
for(unsigned int i = 0; (field = mysql_fetch_field(result)); i++) {
headers[i] = field->name;
if (strcmp(field_name, headers[i]) == 0) {
name_field = i;
}
}
while ((row = mysql_fetch_row(result))) {
//do something with row[name_field]
printf("Name: %s\n", row[name_field]);
}
mysql_free_result(result);
精彩评论