Cocoa and MySQL - parsing data...

Discussion in 'Mac Programming' started by RIRedinPA, May 18, 2011.

  1. macrumors newbie

    Joined:
    May 18, 2011
    #1
    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:

    Code:
    
    - (IBAction)dbConnect:(id)sender {
        
    	
    	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    	MYSQL conn;
    	mysql_init(&conn);
    	
    	if (!mysql_real_connect(&conn, "10.1.1.99", "*******", "******", "oldphotoarchive", 0, NULL, 0)) {
    		NSLog(@"%@", [NSString stringWithUTF8String:mysql_error(&conn)]);
    	} else { 
    		int results = mysql_query(&conn, "SELECT * FROM photorecord");
    		if (results == 0)  { 
    			
    			MYSQL_ROW row;
    			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?
     
  2. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    I know absolutely nothing about MySQL. So this is all based on reading their manual. I am assuming you did the same.

    The signature for this function is
    Code:
    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
    Code:
    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.
     
  3. macrumors Pentium

    KnightWRX

    Joined:
    Jan 28, 2009
    Location:
    Quebec, Canada
    #3
    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 ?

    http://dev.mysql.com/doc/refman/5.6/en/mysql-num-fields.html
     

Share This Page