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.

Here we are with another sub-post related to the main original post that is aimed to describe how to interact with MySQL from C++ using mysql-connector (MySQL C++ with mysql-connector).

Because of the length of such post, given all the satellite configurations and tasks that need to be performed in order to achieve the goal, I decided to split it, generating few articles that are topic on their own.

This is one of them.

So, although this post is focused on installing and configuring MySQL, with few usage example, it is mainly intended to be seen in the context of the bigger picture represented by the main post: MySQL C++ with mysql-connector

 

I already have installed MySQL on my machine but I will follow the configuration sequence again to guide you through this process.
This means that some of the screens during the installation and the final one could differ from what you will, simply because this will be an additional installation on my side. This is actually even more interesting because I believe helps even better in understanding how this system works.
That said, let’s see how it’s done.

MySQL – Download
Let’s download it from here:
Then select the web version that will download the installer when you will execute the installer itself or the fully offline version. I opted for the second option here:
In a similar way as we downloaded the connector, we need to select to login or just download the file:
MySQL – Install
Run the installer and select the Install MySQL Products option:
Here is where you could probably see a different number for your selected port.
I already have mysql installed and configured on port 3306, therefore I will use the suggested port 3307. Let’s keep this in mind when we will connect to it from C++.
Select a strong password if you intend to use this for important stuff as well:
For the same reason explained above, the service name will have a name that could be different from the one you will see in your installation.
There is no problem there, we just need to keep it in mind when we will use it later on.
My one will be named “MySQL56”:
At the end of the installation it should start immediately MySQL Workbench:
Create a DB – Connect to our MySQL Instance
It’s time to create our sample database before writing any code to connect to it (this is related to the other topic, but it is valid as an example to show how to use MySQL and the Workbench in particular).
So, open MySQL Workbench from your Windows Start Menu (if you clodes it):
When the workbench starts you will see your available connections.
They are two in my case (for the reason explained above), so just click on your instance:
and insert the password once requested:
If everything is OK, then you should not see any error (of course) and be presented with a screen similar to this:
Create a DB – Create a sample DB
Click on the forth icon to create a new schema in the current server:
Let’s call it “cpptest” and click “Apply”:
It should be now listed amongst the other schemas:
Time to add a table to it!
Create a DB – Adding a table
Expand the cpptest entry and right click on “Tables”, selecting then “Create Table…”:
Edit it giving it a name (“contacts” for example) and three fields.
Note that to add the fields you just need to double click into an empty row of the column list table.
The first field should be automatically configured, named “idcontacts”, set as primary key and with Datatype “INT”.
Check the “AI” (Auto Increment) check-box, accept it and edit the other two:
  • name, VARCHAR(45)
  • surname, VARCHAR(45)
Then click “Apply”:
Create a DB – Adding records to the table
To add some sample records to the table, right click on it and choose the entry:
“Select Rows – Limit 1000”:
and click “Apply”:
confirm the script clicking Apply and then Finish:
Repeat the process entering a series of names that you want to insert.
Note that the idcontacts column is automatically filled up for us (remember the Auto Increment flag):
As usual Apply and Finish.
We are Happy with our collection:
Create a DB – Adding records to the table
Time to create a new user that will have privileges to use this DB.
Click on the “Users and Privileges” Management option and enter your root password if required:
Click then on the “Add Account” button at the bottom of the just opened panel:
Fill-up the fields choosing a username (I used “cppuser”) and a password (as strong as you prefer). Click then Apply once ready:
Select the user from the left panel, open the “Schema Privileges” tab and click on “Add Entry…”:
In the new window select the “Selected Schema:” option and select our database “cpptest”, then click “OK”:
Select then all the options in the “Object Rights” column (SELECT, INSERT, etc.) and click “Apply”:
Job done here!
We can switch to Visual Studio for the code part (at last!)
It is time to go back to the main article: MySQL C++ with mysql-connector

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.

 

Boost Libraries Installation

January 25th, 2015 | Posted by riccardotramma in Boost | C++ | Download - (0 Comments)

This post is really a subpost 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 one 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 fint it there:

Let’s enter in the core of the topic now!

 

Boost Libraries (1.56.0) – Download
Let’s download them here:
Just click on the Download link:
Click then on the zip file:
Once downloaded extract it, for example in the same lib folder, so you should now have:
Boost Libraries (1.56.0) – Install
Enter into the boost_1_56_0 folder and execute the file “bootstrap.bat“:
C:\libs\boost_1_56_0>bootstrap.bat
The output should be: 
The next step, is to execute “.\b2”. We could use some parameter here, such as:
b2 install –prefix=PREFIX 

where PREFIX is a directory where you want Boost.Build to be installed.
Optionally, add PREFIX/bin to your PATH environment variable. 

We will be ok with the default setting, therefore we will just execute:

C:\libs\boost_1_56_0>b2 install
It will start to compile the code… it will take a bit and a loooong output.
The initial part will be something along this line:

 

Once this is done you should see a new folder on your drive: “C:\Boost\
This is how the situation should look like at this point:
That’s it for this part.
As mentioned this is a subpart I splitted from a larger topic.
If you want to continue the reading of the original topic that originates this continue here: MySQL C++ with mysql-connector
Thanks and share and comment if you find this useful or interesting.