C++, Linux

How To Connect C++ To Mysql in Linux

There is a great library for C++ and Mysql called mysql++. Today we will see a simple example on how to connect to a mysql database and execute a simple select query using this library.

Let’s see the code!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <mysql++.h>
#include <iostream>
 
using namespace std;
using namespace mysqlpp;
 
int main(){
	Connection myconn(false);
	if(myconn.connect("database_name", "localhost", "user_name", "user_password")){
		Query query = myconn.query("select ID, Name from persons");
		if (StoreQueryResult result = query.store()) {
			cout<<"ID"<<'t'<<"Name"<<endl;
	            for (size_t i = 0; i < result.num_rows(); ++i) {
        	        cout<<result[i][0]<<'t'<<result[i][1]<<endl;
        	    }
        	}
	        else {
        	    cerr << "Error: Unable to get data - " << query.error() << endl;
        	    return 1;
        	}
 
		return 0;
	}
	else{
		cerr<< "Error: Unable to connect to database server - "<<myconn.error()<<endl;
		return 1;
	}
}

To compile the above code execute the following command (at this point you must have mysql++ library already installed):

My system is Ubuntu. Your directories’ paths may vary for your distribution. Adjust them accordingly.
IMPORTANT! Pay attention to the order of arguments.

g++ -I/usr/include/mysql -I/usr/include/mysql++ -L/usr/lib/mysql -o connector_example connector_example.cpp -lmysqlpp -lmysqlclient