View Full Version : Cocoa and MySQL - parsing data...

May 18, 2011, 11:30 AM
In my app I am able to connect to a MySQL db and perform a query but I am having problems parsing the returned data. Here's my code:

- (IBAction)dbConnect:(id)sender {

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
MYSQL conn;

if (!mysql_real_connect(&conn, "", "*******", "******", "oldphotoarchive", 0, NULL, 0)) {
NSLog(@"%@", [NSString stringWithUTF8String:mysql_error(&conn)]);
} else {
int results = mysql_query(&conn, "SELECT * FROM photorecord");
if (results == 0) {

unsigned int num_fields;
unsigned int i;

num_fields = mysql_num_fields(results);

NSLog(@"%i", num_fields);

[pool release];

I keep getting an warning that num_fields makes a pointer from integer without a cast, but wouldn't mysql_num_fields() return an integer? And let me take this moment to whine about the lack of a mysql_fetch_array or mysql_fetch_assoc in the C API...

Rereading my question should I be assigning results to something other than an int?

May 18, 2011, 11:36 AM
I know absolutely nothing about MySQL. So this is all based on reading their manual (http://dev.mysql.com/doc/refman/5.0/en/mysql-num-fields.html). I am assuming you did the same.

The signature for this function is
unsigned int mysql_num_fields(MYSQL_RES *result)

So it does return an unsigned int. As expected. It also expects to be passed a pointer to a MYSQL_RES (which I assume is a structure).

Your code is

int results = mysql_query(&conn, "SELECT * FROM photorecord");
num_fields = mysql_num_fields(results);

So, quite obviously, your results variable is of the wrong type. This may well compile and actually might well work on some platforms (where pointers have the same size as ints) but it's to be avoided. It'd take a good look at the example in the manual page I linked to and correct your code.

May 18, 2011, 03:52 PM
You're missing a call in there. You can't take the return value from mysql_query() and feed it into mysql_num_fields(). mysql_query() returns an int, which is simply an indication of whether your query succeeded or failed. mysql_num_fields actually wants a structure pointer to the results themselves. You need to fetch those first with mysql_store_result().

Have you read the C API reference ?