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

– MySQL C API

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;
MYSQL_ROW row;
int query_state;

int main() {
//Connects to MySQL DB
mysql_init(&mysql);

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;
}

mysql_free_result(result);
mysql_close(connection);
}

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:

./a.out

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 *