tags:

views:

448

answers:

1

I am using the "MySQL C API" to query the database and I have the results stored in MYSQL_ROW types. I am able to use print the results to the console with printf("%s", row[0]), however, according to the MySQL C API documentation, I cannot use them as null-terminated strings.

At the bottom of http://dev.mysql.com/doc/refman/5.0/en/c-api-function-overview.html, they say I can "extract" the information with mysql_store_result() or mysql_use_result(). However, I am still confused as to how this is done.

Ideally, I want to the results out as a string so I can do stuff like strcmp, etc but else I definitely need to use the information somehow with those two functions.

Can somebody show me an example of how to do this?

Thanks

+1  A: 

Basically, you call mysql_store_result() or mysql_use_result() to access the result set, the former loads all the rows into memory on the client side, the latter accesses rows one at a time from the server. If you use mysql_use_result(), you need to call mysql_fetch_row() to access each row until the function returns NULL. Each successful call to mysql_fetch_row() will return a MYSQL_ROW which you can use to access the individual field values.

Since the fields are not nul-terminated, you need to use mysql_fetch_lengths() to get the lengths of each of the fields so that you can copy them somewhere else via memcpy, etc.

Since the field values are not nul-terminated you will need to add your own NUL character when you make the copy if you want to use it as a string. Be aware that the field values may contain binary data, so if you do treat it as a string, functions that expect a C string will stop processing data if it encounters a nul-character in the data.

Here is an example from the documentation that should help you put all this together:

MYSQL_ROW row;
unsigned int num_fields;
unsigned int i;

num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result)))
{
   unsigned long *lengths;
   lengths = mysql_fetch_lengths(result);
   for(i = 0; i < num_fields; i++)
   {
       printf("[%.*s] ", (int) lengths[i], 
              row[i] ? row[i] : "NULL");
   }
   printf("\n");
}
Robert Gamble
Thanks so I can get the length but what if I need to get something that is stored as a varchar in the database? Does this mean I can't use strcmp with the results?
Steve
mysql_fetch_lengths() returns the size of each field in a particular row, this can be different for the same column of each row.
Robert Gamble
No, you cannot use strcmp() because the field value will not be nul-terminated, use memcmp() or strncmp() instead.
Robert Gamble