stevesearle.com

© Steve Searle 1999, 2006
Created and maintained using

This page documents how to use a MySQL Database from a C++ program.
I found it took a bit of working out to get the compile
options correct, and created this program to check I had it all
working correctly.
If you have problems compiling or linking, please check my FAQ page before contacting me.
To compile this program, the following command is required:
g++ mysql_example.cpp -o mysql_example -Wall
-I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient
where
/usr/include/mysql is the path to
mysql.h and
/usr/lib/mysql is the path to
libmysqlclient.so. Enter
locate mysql.h
and
locate libmysqlclient.so
to find these
paths.
#include <iostream>
#include <stdio.h>
#include <mysql.h>
int main() {
MYSQL mysql;
MYSQL_RES *pResult;
MYSQL_ROW row;
mysql_init(&mysql);
cout <<
"Connecting ...
\n";
if
(!mysql_real_connect(&mysql,
"angie",
"steve",
"letmein",
"mysql",
0,
NULL,
0))
{
fprintf(stderr, "Failed to connect to database: Error:
%s\n",
mysql_error(&mysql));
}
cout <<
"Selecting data ...
\n";
if
(mysql_query(&mysql,
"select
User, Host from user"))
{
fprintf(stderr, "Failed to select from user table:
Error: %s\n",
mysql_error(&mysql));
}
pResult = mysql_store_result(&mysql);
if (!pResult)
{
fprintf(stderr, "Failed to store results: Error: %s\n",
mysql_error(&mysql));
}
cout <<
"There are "
<< mysql_num_rows(pResult) <<
" users.\n";
while ((row =
mysql_fetch_row(pResult)))
{
cout << "\t" << row[0] << "@" << row[1] << "\n";
}
cout <<
"Freeing memory used
for the reult set ...\n";
mysql_free_result(pResult);
cout <<
"Closing ...\n";
mysql_close(&mysql);
cout <<
"Finishing ...\n";
return 0;
}