Ulf Wendel

MySQL Connector/C++: Guide on building a windows client using Visual Studio (for Dummies)

These materials have been created in April 2009 and are outdated. No promises this still works.

Hello World!

Little idiots (culture clash – “Dear, Dummies”), please find a tutorial on how to compile a command line client using the MySQL Driver for C++ with Visual Studio."Little idiot" may sound offending to native speakers. But it is spot on to describe my skills about compiling a Connector/C++ client on Windows. I need step-by-step instructions including screen shots. You will find them below.

The Internet Super Hero has started as a Little Idiot. Back in 1999 and ealier little idiots speaking german and trying to learn how to use MySQL loved Guido Stepkens MySQL introduction at http://www.little-idiot.de/mysql/mysql.html. Thank you for this early contribution to MySQL 3.23 and PHP 3, Guido! I still love the URL – little-idiot.de.

Contents


Required software

Please make sure that you have the following software installed:

If you plan to build the driver from source, which is not subject of this tutorial, you will also need the following. Please check MySQL Connector/C++: compiling, using and debugging for hints on building the driver itself.

The MySQL Connector/C++ is linked against the MySQL Client Library (AKA libmysql – the C-API). There may be extra download packages for Windows which only contain the MySQL Client Library and related files. However, how do you want to test your new C++ based client, if you have no running MySQL Server at hand. Get the MySQL Server 5.1. Little-idiot pitfall: make sure to install the required Developer Components. Choose Custom Setup when running the MySQL Server Setup Wizard. Select Developer Components – C Include Files / Lib Files.

Install Developer Components!

Installing MySQL Connector/C++ on Windows

As of 1.0.4beta you can use a MSI Installer to install the driver on your system. Running the installer does not require any special permissions. All the installer does is to copy files into your program directory or whatever else target directory you choose.

Welcome to the MySQL Connector C++ Setup Wizard

Go for "Typical". The only optional component that you can install when choosing "Custom" is Debug. However, we have build the Release binaries with debug information (RelWithDeb).

Go for Typical

Hello World!

The source distribution of the MySQL Driver for C++ contains several example programs. All the examples will be build automatically when you build the connector from source. If you do not have the source distribution available, no problem. The basics and a famous "Hello World!" can be found in the MySQL Reference Manual.

/*
examples/standalone_example_docs1.cpp
*/

/* Standard C++ includes */
#include <stdlib.h>
#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 <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' AS _message'..." << endl;

try {
  sql::Driver *driver;
  sql::Connection *con;
  sql::Statement *stmt;
  sql::ResultSet *res;

  /* Create a connection */
  driver = get_driver_instance();
  con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
  /* Connect to the MySQL test database */
  con->setSchema("test");

  stmt = con->createStatement();
  res = stmt->executeQuery("SELECT 'Hello World!' AS _message");
  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;

return EXIT_SUCCESS;
}

Creating a Visual Studio command line client project

You have the driver, you have the "Hello World!" source code. Now you need a new Visual Studio project for building a console application. Start Visual Studio and create a new project using a wizard. Make sure to remember the disk location of your project.

 File->New Project->Visual C++->Win32->Win32 Console Application

Visual Studio project creation wizard

Just click through the wizard, go for all defaults. Note that on the tab "Application Settings" the checkbox "Additional options: Precompiled header" may be checked. Little-idiot pitfall: if is is checked, which has been the default on my Visual C++ 2008 Express copy, you must make sure that all your programs include the header file "stdafx.h".

Visual Studio command line project

Visual Studio project settings for dynamic linking

In the first step we will be linking MySQL Connector/C++ dynamically. This is even easier than static linking. A description on how to link the driver statically can be found below.

Switch from Debug to Release configuration before you proceed. This How-To will demo the creation of a client using the Release configuration. Open the project properties dialog and select configuration properties. Little-idiot pitfall: you are setting the properties for the wrong configuration – make sure your "Configuration" at top of the project properties dialog reads "Active(Release)".

Add the include directory of your MySQL Connector/C++ installation to the Additional Include Directory.

  Project->Properties = ALT + F7
  Configuration Properties -> open tree view
  C/C++ -> General -> Additional Include Directory

Add MySQL Connector/C++ to the Include Directory

Tell the compiler where to find the MySQL Connector/C++ libraries by adding the MySQL Connector/C++ lib/opt directory to the search path.

  Linker -> General -> Additional Library Directories

Add MySQL Connector/C++ to the Library Directory

Now that Visual Studio knows where to search for the driver, we can tell the linker to link the MySQL Connector/C++ libary mysqlcppconn.lib when building the console application.

  Linker -> Input -> Additional Dependencies

Linker Input

You are done. Those are the Visual Studio project settings required to build a dynamically linked program using MySQL Connector/C++.

Compiling/Building the client application

Copy the code of the "Hello world!" example into your main source code file. The "Hello world!" example can be found above or at the MySQL Reference Manual (MySQL Connector/C++ Complete Example 1). Make sure to update the user credentials for logging into the MySQL Server. And, of course, make sure the MySQL Server is up and running.

con = driver->connect("tcp://127.0.0.1:3306", "root", "root");

Remember that you have to add the include file "stdafx.h" to the source code, if you have told the Visual Studio project wizard to use precompiled headers, which has been a default on my Visual Studio 2008 Express.

  Build -> Build Solution = F7

Build

In case of any errors please verify that you have properly set the location of the include and library files as well as the additional input for the linker.

Running the client application

Open a Windows command prompt and change to the build directory of your project. As said before, I have gone for all defaults on Visual Studio 2008 Express. Visual Studio 2008 has created the project in my Documents and Settings directory. After a successful build you will find at least one file in the build directory: <project_name>.exe. Depending on the default debug information settings you may find also a program database file: <project_name>.pdb.

  Start Windows command prompt

Build

Try to run the client application. It is likely that you get an error stating that the "mysqlcppconn.dll" was not found.

The application has failed to start because mysqlcppconn.dll
was not found. Re-installing the application may fix the problem.

Die Anwendung konnte nicht gestartet werden, weil 
mysqlcppconn.dll nicht gefunden wurde. Neuinstallation 
der Anwendung könnte das Problem beheben.

This is not a bug. You need to tell Windows where to find all dll-files required for running an application. In this particular case the application needs "mysqlcppconn.dll" to run. In other cases it may need "libmysql.dll" or any other dll. You can fix this by doing any of the following:

  • Copy mysqlcppconn.dll into you Windows system directory
    • Pro: every user will find it.
    • Con: your setup may become confusing and messy when installing multiple versions of MySQL Connector/C++
  • You add the location of the "mysqlcppconn.dll" to your path setting, for example using SET PATH=%PATH%;C:\path\to\mysqlcppconn.dll
    • Pro: it is easy to do
    • Con: your setup may become confusing and messy in case you have multiple versions of MySQL Connector/C++ in your path
  • You copy "mysqlcppconn.dll" into the current working directory
    • Pro: best control as the current working directory is usually in the path prior to any custom settings
    • Con: you need to for every working directory

It is your choice. I usually either copy the required dll into the current work directory or go the stony way of fixing my path settings.

  Start Windows command prompt
  Fix path setting (see above), if need be

Hello World!

Visual Studio project settings for static linking

Linking a client against the static version of the MySQL Driver for C++ is a little more complicated. Its the same basic procedure of editing the include and library settings of your Visual Studio project. But there is a huge pitfall. Something that neither a beginner nor an advanced user would expect. Lets go through the easy part first.

Create a new project as described above. Modify the project properties. Add the include directory of your MySQL Connector/C++ installation to the Additional Include Directory.

  Project->Properties = ALT + F7
  Configuration Properties -> open tree view
  C/C++ -> General -> Additional Include Directory

Add MySQL Connector/C++ to the Include Directory

To link against the static version of the driver we need to tell the Linker where to find "mysqlcppconn-static.lib" and "libmysql.lib". The first is the static version of the MySQL Connector/C++. It can be found in the installation directory of the MySQL Driver for C++ (C:\path\to\MySQL Connector/C++ 1.0.4.0\lib\opt). The latter is the MySQL Client Library. You should have installed the MySQL Client Library along with the MySQL Server. It is located in the installation directory of the MySQL Server (C:\path\to\MySQL Server 5.1\lib\opt). Add both directory to the list of additional library directories.

  Linker -> General -> Additional Library Directories
  Add MySQL Connector/C++ library directory

Add MySQL Connector/C++ to the Library Directory

Yes, that the above screen shot is from my dynamic project. But its the same dialog, the same procedure…

  Linker -> General -> Additional Library Directories
  Add MySQL Client Library library directory

Add MySQL Client Libary to the Library Directory

As said, you need to link both "mysqlcppconn-static.lib" and "libmysql.lib". Add both to the list of additional dependencies.

  Linker -> Input -> Additional Dependencies

Linker Input

Glory detail: CPPCONN_PUBLIC_FUNC=

Copy the "Hello World!" example into you main source file. Follow the hints from above, if you have issues. Try to build the client application. It should fail. The error message may seem cryptic to you.

IMPORTANT: CPPCONN_PUBLIC_FUNC


1>------ Rebuild All started: Project: cpp_static_client, Configuration: Release Win32 ------
1>Deleting intermediate and output files for project 'cpp_static_client', configuration 'Release|Win32'

1>------ Rebuild All started: Project: cpp_static_client, Configuration: Release Win32 ------
1>Deleting intermediate and output files for project 'cpp_static_client', configuration 'Release|Win32'
1>Compiling...
1>stdafx.cpp
1>cpp_static_client.cpp
1>Linking...
1>cpp_static_client.obj : error LNK2001: unresolved external symbol __imp__get_driver_instance
1>cpp_static_client.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) public: int __thiscall sql::SQLException::getErrorCode(void)const " (__imp_?getErrorCode@SQLException@sql@@QBEHXZ)
1>cpp_static_client.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) public: class std::basic_string<char ,struct std::char_traits<char>,class std::allocator</char><char> > const & __thiscall sql::SQLException::getSQLState(void)const " (__imp_?getSQLState@SQLException@sql@@QBEABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>C:\Dokumente und Einstellungen\T60\Eigene Dateien\Visual Studio 2008\Projects\cpp_static_client\Release\cpp_static_client.exe : fatal error LNK1120: 3 unresolved externals
1>Build log was saved at "file://c:\Dokumente und Einstellungen\T60\Eigene Dateien\Visual Studio 2008\Projects\cpp_static_client\cpp_static_client\Release\BuildLog.htm"
1>cpp_static_client - 4 error(s), 0 warning(s)

All you need to fix this the Preprocessor Definition CPPCONN_PUBLIC_FUNC=. Library functions need to have a different signature on Windows depending on how you want to link them. During the source build of the MySQL Connector/C++ this detail is hidden from you. But if you link your own client applications against the static driver library you need to be aware of this glory detail. Experts may want to have a look at the include file "build_config.h". I, the Internet Super Hero, have left this to my co-worker Lawrin who works frequently on Windows and I simply set CPPCONN_PUBLIC_FUNC= as advised. Make sure you use CPPCONN_PUBLIC_FUNC= and not CPPCONN_PUBLIC_FUNC. You must define it as an empty string.

  C/C++ -> Preprocessor -> Preprocessor Definitions

IMPORTANT: CPPCONN_PUBLIC_FUNC

Rebuild your project. You get a long list of messages. But the last line should read: "Rebuild All: 1 succeeded, 0 failed, 0 skipped". All the messages are warnings not errors.

  Build -> Rebuild Solution = Ctrl+Alt+F7

Static build: warnings but no errors!

You can now start a Windows command prompt and invoke your static client. If you have issues running the client because dll’s cannot be found, check above for a solution.

IDE code completion

You are ready to start using the driver. The API is derived from JDBC. Good JDBC introductions and books are all around. And there are about a dozen examples programs in the examples/ directory of the source distribution. You don’t need anything else. Or maybe some code completion would be useful as you are using an IDE anyway?

Go to the Solution Explorer. Open the tree view of your project. Select the Header Files folder. Use the context menu to add existing items to the header files. Add all header files that ship with the MySQL Connector/C++-

  Solution Explorer -> Your project -> Header Files
  -> Add -> Existing Item...

Add header files for code completion

Open the Class View to browse the classes from sql.mysql namespace. Although our tests do not claim to be perfect usage example they may help you understanding the API. However, we have tried to document all JDBC difference in the Reference Manual. Backed up with code completion and the example programs from the source distribution you should have all the code snippets for building basic applications using Cut&Paste.

  Class Browser

Add header files for code completion

Swimming pool

As I am a little-idiot myself when it comes to Windows, please meet the dolphins at the swimming pool. Ask your question on the MySQL Connector/C++ forum at http://forums.mysql.com/list.php?167.

Comments are closed.