Articles
MySQL in Cocoa using MCPKit
December 22, 2006 (cocoa, mysql)
Unpackage the source and keep the folder handy.
Create a new cocoa project in xcode. Name it what you will. I named mine mysqlTest
In your new cocoa app open the frameworks disclosure until you see 'linked frameworks'. Click linked frameworks and then go to the top menu and click Project -> Add to Project. When the dialogue appears browse into the CocoaMySQL directory from above. In the root of CocoaMySQL will be MCPKit_bundled.framework. Select this framework to be included in your project. Copy the files over when it asks if you want to.
The reason we are using CocoaMySQL to secure the framework as opposed to downloading the framework from the MCP website is that website only has a powerPC version at this time. this is due to the intel version of the mysql library being unavailable, according to the site. The clever folks at cocoaMySQL have modified the framework to be universal. Hence we use theirs.
In Xcode, select 'targets' from the left hand menu. Open the diclosure icon to see the name of your program, open that triangle to see a list of build tasks. Right click your program name and select add->new build phase -> new copy files build phase. In the dialogue that is presented select frameworks from the drop down list. Nothing else needs to be done, so close the window. This will create a new section named 'copy files'. Now drag the framework you included under linked frameworks to the new copy phase.
Now it is time to code.
Depending on the type of program you created you need to decide where to place the following code. In my example, I created a button using interface builder and create an action that wires to the controller. In xcode I added the following code to the action.
- (IBAction)pingDB:(id)sender
{
NSLog(@"Getting data from MySQL...");
MCPResult *theRes;
NSString *user;
MCPConnection *theConnec = [[MCPConnection alloc] initToHost:@"localhost"
withLogin:@"root" password:@"" usingPort:0];
if ([theConnec isConnected])
NSLog(@"Connected :)");
else
NSLog(@"Not Connected :(");
if ([theConnec selectDB:@"aphrodite"])
NSLog(@"Database selected :))");
else
NSLog(@"Database not selected :(");
theRes = [theConnec queryString:@"select * from users"];
if ([theRes numOfRows])
NSLog(@"Rows inserted :)))");
else
NSLog(@"No Rows :(");
user = [[theRes fetchRowAsArray] objectAtIndex:1];
NSLog(@"User name is %@", user);
}
This code utilizes the MCPKit framework to access the mysql server, tap into a database, run a query and spit out some results. You need to put the following import at the top of the .h and .m files for your controller.
#import <MCPKit_bundled/MCPKit_bundled.h>
When you run the xcode program it should compile and present you with a page with a button. Hit the button and watch the console. You should see a success message.
Of course all this depends on you having a properly installed, running and populated mysql database. That's beyond the scope of this how-to.
