Dejan Levec

Use MySQL database in your C++ projects

How to use MySQL DB in your C++ projects. This tutorial is written for Debian Lenny/Ubuntu 9.10. With a few minor changes, it should work on other distributions also.

What will you need?

– gcc <– c++ compiler

– MySQL server 5.0 installed


To install above programs run this command as root:

apt-get install build-essential mysql-server mysql-client libsoci-mysql-gcc

When you have everything installed you need to create database and add user.

Now you will need to add a new table. The easiest approach is to use phpMyAdmin.

Simple program to test MySQL C API (copy it and save as filename.cpp):

#include <iostream>
#include <mysql.h>

using namespace std;

//MySQL variables
MYSQL *connection, mysql;
MYSQL_RES *result;
int query_state;

int main() {
//Connects to MySQL DB

connection = mysql_real_connect(&mysql, \"localhost\", \"username\", \"password\", \"database\", 0, 0, 0);

//Checks if there was a problem with connection
if(connection == NULL) {
cout <<mysql_error(&mysql);
return 1;

//Execute query
query_state = mysql_query(connection, \"SELECT * FROM table\");

if(query_state != 0) {
cout << mysql_error(connection);

//Loads query data
result = mysql_use_result(connection);

//Writes data to stdio from first column on all rows in table
while((row = mysql_fetch_row(result)) != NULL) {
cout << row[0] << endl;


You can compile it with following command:

g++ filename.cpp -L/usr/include/mysql -lmysqlclient -I/usr/include/mysql

If there was no error displayed then your program compiled successfully. You can run by typing:


And now you made your first C++ program that gets data from MySQL DB. You can do a lot more than just that.

You will probably need to read MySQL C API manual to learn other commands.

Leave a Reply

Your email address will not be published. Required fields are marked *