MySQL with C++

Here’s an example for connecting C++ program with MySQL.

You can simply download code from Github [Link]


Do as following

Write following code in text editor and save file as mysql.cpp

// Include Header Files
#include <iostream>
#include <cstdio>
#include <cstdlib>

// For MySQL Connection
#include <mysql.h>

using namespace std;

// Defining Constant Variables
#define SERVER "localhost"
#define USER "root"
#define PASSWORD "password"
#define DATABASE "test"

int main()
    MYSQL *connect;
    connect = mysql_init(NULL);

    if (!connect)
        cout << "Mysql Initialization Failed";
        return 1;

    connect = mysql_real_connect(connect, SERVER, USER, PASSWORD, DATABASE, 0,NULL,0);

    if (connect)
        cout << "Connection Succeededn";
        cout << "Connection Failedn";

    MYSQL_RES *res_set;
    MYSQL_ROW row;

    // Replace MySQL query with your query

    mysql_query (connect,"show tables");

    unsigned int i=0;


    unsigned int numrows = mysql_num_rows(res_set);
    cout << " Tables in " << DATABASE << " database " << endl;

    while (((row=mysql_fetch_row(res_set)) !=NULL))
        cout << row[i] << endl;

    mysql_close (connect);

    return 0;

Now compile and run this program in terminal using following statements.

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

$ ./mysql

MySQL Connector for C++

MySQL Connector/C++ is a MySQL database connector for C++.


If you are using Linux then you need to install two additional packages i.e. libmysql++ and libmysql++-dev for connecting C++ program with MySQL

Run following commands in terminal.

$ sudo apt-get install libmysql++

$ sudo apt-get install libmysql++-dev