How to c++ mysql mac osx
posted on: 2011-03-22 11:04:12
I thought that I would make a simple post on how to set up mysql c++ connector on mac osx, I am using Snow Leopard.
First off you need to download the relevant server package: http://dev.mysql.com/downloads/mysql/.
Next you will need to add the following search paths in your xcode project.
In the build settings [Project -> Edit Project Settings -> Build] add the following locations to the search paths settings.
Header Search Paths: /usr/local/mysql/include/
Library Search Paths: /usr/local/mysql/lib/
In the same menu you now need to add the linker flags in the Linking section.
Other Linker Flags: -lmysqlclient -lm -lz
Then you just need to include the header file and your all ready.
#include <mysql.h>
Here is some code to get you started.
std::vector<std::string> tables;
MYSQL_RES *result;
MYSQL_ROW row;
MYSQL *connection, mysql;
int state;
mysql_init(&mysql);
connection = mysql_real_connect(&mysql,"localhost","username","password","database",0,0,0);
if (connection == NULL)
{
std::cout << mysql_error(&mysql) << std::endl;
return tables;
}
state = mysql_query(connection, "SHOW TABLES");
if (state !=0)
{
std::cout << mysql_error(connection) << std::endl;
return tables;
}
result = mysql_store_result(connection);
std::cout << "tables: " << mysql_num_rows(result) << std::endl;
while ( ( row=mysql_fetch_row(result)) != NULL )
{
tables.push_back(row[0]);
}
mysql_free_result(result);
mysql_close(connection);
P.s. If you get any errors like "dyld: Library not loaded: libmysqlclient.16.dylib" try copying the /usr/local/mysql/lib/libmysqlclient.16.dylib library into the same folder as your executable.
