Shravan40 Shravan40 - 21 days ago 4x
C++ Question

How to establish connection with database using MySQLConnectorC++?

I am trying to establish connection with MySQL database in C++ project.
And I followed the instructions given in link.
After installing Cmake, I was facing problem in Build & Install MySQL Connector/C++.

does not exists in directory.
After some search on web, I have found this answer and followed the steps given, but it didn't work in my case.

Frustrated will all this, I copied all the files(Extracted from dowload link of MySQLConnector C++) into my project folder, and trying to establish connection using this piece of code.

/* Standard C++ includes */

#include <cstdlib>
#include <iostream>

Include directly the different headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!

#include "mysql_connection.h"
#include "mysql_driver.h"
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/resultset.h"
#include "cppconn/statement.h"

using namespace std;
using namespace sql::mysql;

void db_connection() {
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://", "root", "root");
/* Connect to the MySQL test database */

stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
/* Access column fata by numeric offset, 1 is the first column */
cout << res->getString(1) << endl;
delete res;
delete stmt;
delete con;

} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;

cout << endl;

But it says,
undefined reference to
, but it is defined in


Finally, i have found the solution :)

First I completely un-installed MySQL from system (MySQL Client, MYSQL Server and libmysqlcppconn-dev).

After that, install all these again again.

  1. Install MySQL Client and Server.
  2. sudo apt-get install libmysqlcppconn-dev

Now ensure you have all dependencies installed

  1. sudo apt-get build-dep libmysqlcppconn-dev

And now build the package using -lmysqlcppconn.