Just Code it!
Header

This post is a tutorial that will explain hot to write a simple C++ code that can be considered the starting point for any other program you intend to write in C++ with the intention to use a MySQL Database.

In order to connect to MySQL from C++ we will use some libraries specifically designed for this purpose.

Despite the concept seems simple, there are a series of gotchas and configurations that can put off the task many people, increasing the amount of work needed and not necessarily forecasted.

This tutorial will reach the goal starting essentially from scratch, where the environment needs to be completely configured… even without Visual Studio!

While writing this tutorial, I decided to split it in multiple sub-posts because of the amount of information I ended up collecting. Doing this will remove some of the noise around the main topic and will allow to follow the post and the specific sections even for people with different requirements that have already available some of the systems I am going to describe.

As a reference, these are the additional posts:

 

Enough said, let’s start the journey! See you at the end of this. Happy reading.

mysql-connector (1.1.4) – Download

First things first… let’s immediately download what we are really interested in, the C++ libraries (source) that will allow us to connect and interact with a MySQL database.

Open the browser to the MySQL website and navigate to the page with the information about the connector:

http://dev.mysql.com/downloads/connector/cpp/

Select the “Source Code” option from the drop-down menu:

Download the generic Windows version:

In the following page select your preferred download option or just download it using the link at the bottom of the page:

Let’s remember the warning reported on the website:

Warning
One problem that can occur is when the tools you use to build your application are not compatible with the tools used to build the binary versions of MySQL Connector/C++. Ideally, you need to build your application with the same tools that were used to build the MySQL Connector/C++ binaries. 

 

Create a folder, for example “C:\libs\” and extract the archive in there.

The structure should look like this:

In order to build the source code for the connector libraries we need to download CMake.

It’s time to switch to the first sub-post if you need to perform this step and install CMake (CMake Installation and usage (Command Prompt Console and GUI)).

Jump to this post and see you here once you are ready to continue (I would suggest you to follow just the initial part of the tutorial, limited to installing it. The remainder will be useful later on and will probably not work on your system if you don’t have everything else already configured): CMake Installation and usage

Back from CMake Installation

I will assume that you have CMake installed on your system now.

mysql-connector 1.1.4 – Build – First Potential Problem (Missing Visual Studio)


If we try to run the CMake command to generate the Visual Studio solution from the mysql-connector code we could potentially immediately receive an error.
Let’s try this using the Command line:

C:\libs\mysql-connector-c++-1.1.4>cmake -G “Visual Studio 10”

If you don’t have the C/C++ compiler then you will see this error:

Pay particular attention to the lines:

If that’s the case, what you need to do is installing Visual Studio.

Visual Studio (C++ 2010 Express)

Let’s download Visual Studio (Visual C++ 2010 Express is ok for us)
Go to the website:
and find the Install Now link:
Install it executing the installation file (vc_web.exe) downloaded.
Then try again!

mysql-connector (1.1.4) – Build – Second Potential Problem (Missing Boost Libraries)

If we try again now:
C:\libs\mysql-connector-c++-1.1.4>cmake -G “Visual Studio 10”
This time it should go further and complain about the (potential) next problem:

 

The main issue is now:

The problem now is that in order to build this code you need to have installed the BOOST libraries.
If that’s the problem you see as well, then you can happily jump to the next sub-post where is explained in detail how to install and configure boost libraries: Boost Libraries Installation
See you when you are ready to proceed!

Back from Boost Libraries Installation

You should now have a system with CMake, Visual Studio and Boost Libraries installed and configured. Time to continue!

mysql-connector (1.1.4) – Build – Third Potential Problem (MySQL not installed)

Go back into the connector folder and execute again:
C:\libs\mysql-connector-c++-1.1.4>cmake -G “Visual Studio 10”

NOTE:

If you decided at any point to move the folder after executing cmake the first time you will potentially see an error:

To quickly fix this, just remove the file “CMakeCache.txt” and run cmake again.

If you don’t have MySQL installed on your system, then you will probably see this error:

The main indicator for this problem is the line:
If that’s what you see as well… well, you know what’s coming. Yep, another sub-post: MySQL Service, Workspace, Users and Tables
Jump to this post and you can read for now just the initial part that covers the download and installation of MySQL.
The rest of that post will show how to create a database, user and table that we will here, but you can go back to that section later on.

Back from MySQL installation

If everything went as planned until this point you should have CMake, Boost libraries,Visual Studio and MySQL installed and ready to rock.

mysql-connector (1.1.4) – Build – Creating the Visual Studio Solution

Now we can go back into our connector folder and try once again to recreate our Visual Studio Solution.
Yhou can follow this step in the CMake tutorial if you want (where it is explained how to obtain the same result using the command line or the GUI).
This is an extract of it, where I will show only the command line option.
If you run the same command again:
C:\libs\mysql-connector-c++-1.1.4>cmake -G “Visual Studio 10”

You should finally succeed in this step, obtaining:
Now, if everything went as planned, you should be able to see a solution file (and other files as well) into your connector’s folder:
Now we can finally open the created solution (MYSQLCPPCONN.sln) with Visual Studio!
Simply double-click on:
MYSQLCPPCONN.sln

Build MySqlCppConn.sln – Debug

In Visual studio, set the configuration to DEBUG and try to Build.
What should happen is that you will see a series of errors:
ERRORS:

Open the properties for the project “mysqlcppconn“. Right-click on it and select “Properties”:

We can do this using different techniques, but I want to use one (even if it is not my preferred one) just for a change :).

 

Make sure to be in the configuration “Debug” and go in the section:

Common Properties -> Linker -> Input

 

Open the “Additional Dependencies” drop-down list and click on “<Edit…>”:

Substitute the entry:

  • C:\Program Files\MySQL\MySQL Server 5.6\lib\mysqlclient.lib
with:
  •  C:\Program Files\MySQL\MySQL Server 5.6\lib\debug\mysqlclient.lib

If you build now you could receive another error:


Open the project properties for the project “mysqlcppconn-static

Go in the section:
Common Properties -> Librarian -> Command Line
and change the additional options from:
  • C:/Program Files/MySQL/MySQL Server 5.6/lib/mysqlclient.lib
to:
  •  “C:/Program Files/MySQL/MySQL Server 5.6/lib/debug/mysqlclient.lib”
including the quotes
Build again and everything should be ok now!

Build MySqlCppConn.sln – Release

For the release build the only fix I had to do was only the “Additional Options” section in the Librarian -> Command Line

section for the “mysqlcppconn-static” project (in Release configuration).

Add the quotes to:

  • C:/Program Files/MySQL/MySQL Server 5.6/lib/mysqlclient.lib
Also in this case you should receive a successful compilation:

 

Libraries

If you open now the window explorer in the connector folder, in the sub-folder “driver”:
C:\libs\mysql-connector-c++-1.1.4\driver
you should see the two build folders “Debug” and “Release”:
Inside these you should find at least the three files:
  • mysqlcppconn.dll
  • mysqlcppconn.lib
  • mysqlcppconn-static.lib
We are ready to use it finally!

Creating a DB

It is finally time to create a database in MySQL that we will use in C++.
You can refer back to the post already highlighted previously (MySQL installation and Usage) and continue to follow it from where you left it until the end.
In that tutorial I explain how to create a sample DB with a sample user that will have access rights and a sample table that we will be able access from code.
When that system is ready, is time to jump into the final step!

Coding – Create a new Visual Studio Solution

In Visual Studio create a new project (I selected a simple Win32 Console Application)
Right click on the source folder and add a new cpp file:
Let’s give it a simple name (the very original “main.cpp” :P):
You should see the new file added:
Before writing any code, let’s configure our environment setting up the folder and libraries that we need to use/reference in order to successfully build our app.

Coding – Configure the Environment


Open the properties window of the project and go to the settings page:
Configuration Properties -> VC++ Directories
And edit the entry:
Include Directories
Make sure you are in the “All Configurations” configuration:

Edit it adding the lines:

C:\libs\mysql-connector-c++-1.1.4\cppconn

C:\Boost\include\boost-1_56

Edit then the Library Directories property, adding the line:

C:\libs\mysql-connector-c++-1.1.4\driver\$(Configuration)\

Edit then the property in:

Configuration Properties -> Linker -> Input -> Additional Dependencies

adding the line:

mysqlcppconn.lib

One last step you may need to do is copying the “libmysql.dll” and “copy “mysqlcppconn.lib” into your output folder.

Just open the properties to:

Configuration Properties -> Build Events -> Post-Build Event

Then edit “Command Line” and type in this (or the equivalent line that you need in order to copy the missing dll to the output folder):

copy “C:\Program Files\MySQL\MySQL Connector C 6.1.5\lib\libmysql.dll” “$(OutDir)”

copy “C:\libs\mysql-connector-c++-1.1.4\driver\$(Configuration)\mysqlcppconn.dll”  “$(OutDir)”

Remember to edit All Configurations:

Finally it’s time to code!

Coding – Code: Connecting to MySQL

Open the “main.cpp” and let’s put some code.

The first simple code will just test the library, connecting to the DB (our one) using the user that we previously set-up in MySQL Workbench.
Remember to configure correctly:
  • The database address (and port)
  • The User and Password for your user
  • The Database name (that contains the “contacts” table)
That’s the simplest code with some error handling:

If your run this code and you didn’t set-up correctly one of the used parameters, then you will see the error text (without crashing). If that’s the case, check your parameters and verify that you will see the “Connection to the DB established!” string.

Coding – Code: Connecting and using the DB

For the final part of this post we are going to see how to connect now to our DB and retrieve and print the data from our table!
The new lines are the ones that follow the connection established message and few extra includes.
I will omit any exception handling to keep the code short and simple.
This is the final code:

If you build and run the code, you should be finally happily able to see the rows that we entered in our table using MySQL Workbench!


 

That’s all!

 

Of course you can now play around with it inserting, editing, removing entries. For these functionalities and more advanced one I point you to the official website and in particular to the Developer Zone:
Please Link and comment if you found this interesting or useful.

As for other posts (see Boost Libraries Installation), this post is actually a sub-post I made while I was writing a larger post where I explain how to download and use MySQL connector C++ libraries (MySQL C++ with mysql-connector).

That post soon became pretty big due to the amount of stuff you need to configure in order to achieve the goal, therefore I decided to split it in smaller posts that on one side are useful on their own and on the other helps in keeping the main post they came from slightly smaller and easier to follow. Because of this I will keep these posts quite short.

If you are interested in this post as well, you can find it there:

For this example I will use MySQL Connector for C++ as a sample to show the usage of CMake to generate Visual Studio solutions.

Let’s start!

 

CMake (3.0.2) – Download and Install

In order to build the source code for the connector libraries we need to download CMake
Go to the CMake website:
and download it:
Select the Installer in this case:
Execute the installer. I selected the option to add it to the system PATH for an easy access:
Just go Next until the end and Install it.
CMake (3.0.2) – Test
To test that everything is ok with cmake, open a command console and go into the folder where we extracted the connector code and execute:

C:\libs\mysql-connector-c++-1.1.4>cmake

 

We should see this output:

We can generate the Visual studio project in two ways:

  • Using the GUI
  • Using the command line

 

 

CMake (3.0.2) – Usage from Command Line to generate the Visual Studio Solution
At this stage, if you are following the MySQL connector tutorial () you want probably to go back to follow the rest of the tutorial, where you will install first all the required libraries and systems that you need in order to successfully execute the next command.
If you did instead all the required step and everything is correctly configured or you want just to see an example of the usage of CMake for this purpose, then keep reading.

Now we can go back into our connector folder and try once again to recreate our Visual Studio Solution:
C:\libs\mysql-connector-c++-1.1.4>cmake -G “Visual Studio 10”

Obtaining:

 

Now, if everything went as planned, you should be able to see a solution file (and other files as well) into your connector’s folder:

You can then open the solution and continue from there.
CMake (3.0.2) – Usage from GUI to generate the Visual Studio Solution
An alternative way to generate the Solution file is to use the CMake GUI.
Launch the cmake-gui from the start menu:
In the window that opens select “Browse Source…” button and locate the root of your project.
I will select the one where the code for MySQL Connector has been extracted:
Copy the same path for the binaries, then click on “Generate” (or Configure) and select the IDE you are interested in.
I will select Visual Studio 2010 for this example.
Click “Finish” when ready:
Everything should complete successfully (pay particular attention at the bottom window without being too much scared by the red entries in the main window):
If you try to click once again (or why not… a couple of times as well :P) on the “Generate” button, all the red should disappear from the main window:
Anyway, despite the colouring, you should still be able to see your new solution file generated and ready to be opened in Visual Studio.
Now, if were following the MySQL connector tutorial (MySQL C++ with mysql-connector) you can go back and follow the remaining part of that tutorial.

 

Comment or Leave a Message

Please Comment or Leave a Message if this is what you are looking for or if you have any question/comment/suggestion/request.


To me, one of the most surprising thing about NAnt is that it doesn’t support colours out of the box.
NAnt is an amazing tool that allows to build software through a set of really powerful tasks. You can download it from here: http://nant.sourceforge.net/.
I use it quite a lot in different projects and one thing I always missed is the support for colorised console output.
I think that echoing something using different colours helps a lot, even if only to provide a quick spottable info that can help the user (the guy in front of the pc that is waiting for the build to complete) to understand the build stage (especially if it is a long build with several stages).
As soon as I had some time to spend on it I decided to write this feature myself and here I am, sharing this with whoever needs it for its own personal/business process.
I provide the DLL that you can use freely. If you find it useful the only thing I ask is if you can leave a comment and if you have a web page, add a link to this page to help other users.

What it adds
In brief this is the list of functionalities that you will have:

  • setcolour – to select the current colour
  • pushcolour/popcolour/resetcolour – to manage a stack of colours, so that you can change a colour and go back to the previous when you are done.
  • echocolour – an upgrade to the base echo task that colours the message
  • execcolour – an upgrade to the base exec task that colours the output in case of error (behaviour and error colour configurable)
  • colourfail – an upgrade to any other generic NAnt task, operation or set of operations that colours the output in case of failure (error colour configurable)

The list of tasks that allow to use those functionalities are (in more detail): (Note that you can have this list using the <helpcolour /> task)

Tasks

  • <setcolour [colour=”fc”] [bg=”bc”] [preserve=”tf”] /> – Set the current colour.
  • <pushcolour [colour=”fc”] [bg=”bc”] [preserve=”tf”] /> – Push the color in the stack of colours and set it as current colour.
  • <popcolour /> – Remove the color on the top of the stack and set the previous one as current colour.
  • <resetcolour /> – Reset the colours stack and set the original color as current colour.
  • <seterrorcolour [colour=”fc”] [bg=”bc”] /> – Set the colour to use when an error occurs during the execution of execcolour task.
  • <reseterrorcolour /> – Reset the default error colour (red on black background).
  • <echocolour message=”Message Here” [colour=”fc”] [bg=”bc”] [preserve=”tf”] /> – Echoes the message in the chosen colour.”
  • <execcolour [highlighterror=”tf”] …more… /> – Extends the default exec task adding colours capabilities (use the usual “exec” task parameter here). It shows the error using the error colour and, if used with failonerror=”false” and highlighterror=”true” shows the exec exit code using the error colour if it is different from 0 (and logs it as a warning).
  • <colourfail [colour=”fc”] [bg=”bc”]> …any othe task there… </colourfail> – Extends the failure colour to everything executed inside the colourfail initial and closing tags. E.g. <colourfail> <fail message=”simulated failure” /> </colourfail>
  • <initcolours [silent=”tf”] /> – Initialise the default colour using the current console colour. The default error colour is set to the current error color. Using silent=”true” the DLL version number will not be displayed when the first colour task will be used. NOTE: This task is optional and you can use all other tasks without worrying to use this at any time.
  • <helpcolour /> – Shows this help…

Where:
fc : specify the foreground colour to use.
bc : specify the background colour to use.
[…] : specify an optional parameter.
tf : use “true” or “false” there.
…more… : indicates other parameters.
preserve : Preserve the current fc and/or bc when fc and/or bc is not specified. This is false if unspecified.
highlighterror: This is false if unspecified.

How to set-up
To use this dll, put it somewhere where your NAnt executable can reach it. If you prefer you can directly add it in the same folder of NAnt.exe.
Somewhere at the start of your NAnt script add this line (assuming that it sits in the same folder):

From now on you will be able to access its functionalities in your script.

Feature – Colour Help Command (helpcolour)
Use this task as a reminder for the supported tasks:

Feature – Direct Colour Change (setcolour)
You can use console color using this syntax:

The output is:

Feature – Coloured Message (Echo Extension: echocolour)
A more direct way to output colour messages is using directly the echocolour task:

With this result:

Feature – Use Colour Stack (pushcolour, popcolour, resetcolour)
There is a way to use the colours pushing and popping them in and from a stack. This can be useful when invoking sub targets that have to set the colour for themselves but you want them to restore the colour to the previous one when finished.
This is a simple Example:

With this result:

To reset the stack at any point you can use the resetcolour task. Example:

Result:

This is a more complex example of stack usage:

With this result:

Feature – Exec with coloured failures (Exec Extension: execcolour)
In order to quickly use the exec task but with coloured failures, you can use the execcolours task. Those are some examples:
A Simple exec that fails (Building a solution with an error in it):

This is the output:

An option is to suppress the failure (as in exec task), but force to highlight the error anyway. This is optional:

Result:

Feature – Change Error Colour (seterrorcolour, reseterrorcolour)
The error colour can be changed at any time using seterrorcolour and reseterrorcolour (to bring it back to the default “red” colour):

And this an excerpt of the output:

Feature – Color the failure of any other task (Generic Extension: colourfail)
If you want to highlight the build failure of any other NAnt task or your other custom task, you can still do so using colourfail!
Here is a really simple example of usage:

And the result will be:

Another different example is:

Resulting in:

Of course you can wrap the whole script in this task, having the coloured error feature always active.
An example that shows this is action is the following:

With the expected result:

Feature – Init the default colour and error colour (initcolours)
This task is optional. Everything works even if this is never used.
You must use this as first task if you want to remove the display of the version number that is automatically shown the first time a colour task is used.
When used it will change the default colour and error colour using the current one. This allows to change the result of the task resetcolour and reseterrorcolour.
This is an example:

Result:

Note that the colour of the console is still recovered despite the default colours have been changed.

More about Colours
The colours must be colours recognised by the console. The system is quite robust but it is safer if you specify the colour using the correct case sensitive string. This because the core tries to match the string to an internal enumeration and this is why it needs to match.
In any case, if the colour is not recognised, or simply wrong, an error will fire allowing to fix the mistake.
Example:

Will generate:

Conclusion
I believe this DLL can offer a satisfying set of features to use colours in NAnt with a reasonable degree of flexibility.
Download and use it freely. If you like it, please add a comment and a link to this page to help others benefit of it.
If you have any suggestion, comments or if you want to make a request for something to add in future release, please leave a comment :).