Connecting to Mysql with C++ in ubuntu

 

Today I have to write a program that connects to the database server, Mysql and execute some quires. I have done it many times using java with ease using java sql library, but I have no clue how to do it in C++. Anyways, we have out GOOGLE uncle to ask anything. So, I searched through the web and found Mysql++, which is the C++ wrapper for Mysql’s C API and need to install libmysqlclient-dev library for mysql connection.(use sudo apt-get install libmysqlclient-dev for installation)
I actually started it A Tiny MySQL++ tutorial and was redirected to Installing MYSQL++ on Linux.
After reading the tutorial for installing MySQL++,
1. I downloaded MySQL++ source code from http://www.tangentsoft.net/mysql++/.
2. Extracted the tar file using the command
tar xvfz mysql++-3.1.0.tar.gz
3. cd mysql++-3.1.0/
4. ./configure
5. make (BUZZ…. I have an error.
./ssx/genv2.cpp: In function ‘bool generate_ssqls2(const char*, const ParseV2*)’:
./ssx/genv2.cpp:70: error: ‘strcmp’ was not declared in this scope make: *** [ssqlsxlat_genv2.o] Error 1)
Again, I searched the web and found a patch for the error. The patch is so simple, all that it is to be done is simply edit the file
./ssx/genv2.cpp
include the header file, string .h to the header file section of the cpp program and run the make again.
Line to be added:

#include <string.h>

now make works perfect.
6. sudo make install
7. Now for,

#include<mysql++.h>

as given in the tutorial of installing MySQL++ edit
/etc/ld.so.conf
,add the line
/usr/local/lib
and save.
8. Run the command
ldconfig
The tutorial says you are done, but I am not done.
Now,I tried to execute the first program to check if the header file

 #include<mysql++.h>

is working or not. The program is so simple

#include<iostream.h>
#include<mysql++.h>
using namespace std;
int main()
{
	cout<<"Hello world";
}

I got the error:
simple.cpp:2:20: error: mysql++.h: No such file or directory.

I searched for a way to include the header files while compiling a cpp program(as we do it with javac -cp when importing packages into a java program) and I found the way out:)

It is:
use the -I Option with g++ and execute the command:
g++ -I /usr/local/include/mysql++ -I /usr/include/mysql/ simple.cpp

The example works perfect. And the output is as expected.

Now, Its the time for me to execute my first connection to MySQL database using the program given in the tutorial. Due to my anxiety I have just copied and pasted the program. The program is:


#include<iostream.h>
#include<mysql++.h>
 
using namespace std;
using namespace mysqlpp;
 
int main() {
    try {
        Connection conn(false);
        conn.connect("DB NAME", "DB HOST probably localhost", "DB USER", "DB PASS");
        Query query = conn.query();
    } catch (BadQuery er) { // handle any connection or
        // query errors that may come up
        cerr << "Error: " << er.what() << endl;
        return -1;
    } catch (const BadConversion& er) {
        // Handle bad conversions
        cerr << "Conversion error: " << er.what() << endl <<
                "\tretrieved data size: " << er.retrieved <<
                ", actual size: " << er.actual_size << endl;
        return -1;
    } catch (const Exception& er) {
        // Catch-all for any other MySQL++ exceptions
        cerr << "Error: " << er.what() << endl;
        return -1;
    }
    cout<<"Sucesss";
}

I changed the DB name, username and password, then tried to compile the program but my previous command:

g++ -I /usr/local/inl++ -I /usr/include/mysql/ simple.cpp

BUZZ….. again, I have few more errors:

simple.cpp:(.text+0×26): undefined reference to `mysqlpp::Connection::Connection(bool)’
simple.cpp:(.text+0×59): undefined reference to `mysqlpp::Connection::connect(char const*, char const*, char const*, char const*, unsigned int)’
simple.cpp:(.text+0×76): undefined reference to `mysqlpp::Connection::query(char const*)’
simple.cpp:(.text+0×92): undefined reference to `mysqlpp::Connection::~Connection()’
simple.cpp:(.text+0xa5): undefined reference to `mysqlpp::Connection::~Connection()’
collect2: ld returned 1 exit status

I have no clue how to solve it, but my heart always said, Don’t worry rams, We have google uncle.
Again went for a hunt in the web for clarifying the errors, and found it in MySQL forums. Its because of the linker problem in the program and the “undefined reference” is best resolved by adding the following to our build:
-L/usr/lib/mysql -lmysqlclient -lmysqlpp.
So, I just gave it a try…..

g++ -I /usr/local/include/mysql++ -I /usr/include/mysql/ -L/usr/lib/mysql -lmysqlclient -lmysqlpp simple.cpp

Yahoo………. I got it compiled. Now simply execute it:
./a.out

and the output is absolutely fine. Then I tried with the second example in the tutorial:

#include<iostream>
#include<mysql++.h>
 
using namespace std;
using namespace mysqlpp;
 
int main() {
    try {
        Connection conn(false);
        conn.connect("DB NAME", "DB HOST probably localhost", "DB USER", "DB PASS");
        Query query = conn.query();
 
        /* To insert stuff with escaping */
        query << "INSERT INTO some_table " <<
                     "VALUES (" <<
                     "'', " << /* This is left empty because the column is AUTO_INCREMENT */
                     "\"" << escape << some_var_that_contains_some_value << "\"" <<
                     ");";
        query.execute();
        /* That's it for INSERT */
 
        /* Now SELECT */
        query << "SELECT * FROM biz LIMIT 10";
        StoreQueryResult ares = query.store();
        for (size_t i = 0; i < ares.num_rows(); i++)
           cout << "Name: " << ares[i]["name"] << " - Address: " << ares[i]["address"] << endl;
 
        /* Let's get a count of something */
        query << "SELECT COUNT(*) AS row_count FROM biz";
        StoreQueryResult bres = query.store();
        cout << "Total rows: " << bres[0]["row_count"];
 
    } catch (BadQuery er) { // handle any connection or
        // query errors that may come up
        cerr << "Error: " << er.what() << endl;
        return -1;
    } catch (const BadConversion& er) {
        // Handle bad conversions
        cerr << "Conversion error: " << er.what() << endl <<
                "\tretrieved data size: " << er.retrieved <<
                ", actual size: " << er.actual_size << endl;
        return -1;
    } catch (const Exception& er) {
        // Catch-all for any other MySQL++ exceptions
        cerr << "Error: " << er.what() << endl;
        return -1;
    }
 
    return (EXIT_SUCCESS);
}

and it is a success again…… Thanks to codehead for the valuable tutorials and MySQL forums for the help…….

i made it….

Connecting to Mysql with C++ in ubuntu

About these ads

One Response to “Connecting to Mysql with C++ in ubuntu”

  1. I installed mysql++ using synaptic package manager rest i followed your steps but i was able to compile the first program and not the second one…..can you suggest anything on what might be wrong.
    Also can you please add tell me the contents of your folder /usr/lib/mysql.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: