Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL C API - Access rows by column name

Tags:

c

mysql

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['authors']. I want to program directly with the C API without any wrappers, and not in C++.

Thanks for your help!

like image 708
wundervoll Avatar asked Feb 06 '11 00:02

wundervoll


1 Answers

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);
like image 102
David Beck Avatar answered Oct 17 '22 19:10

David Beck