How To: Insert data into a MySQL DB using Connector/C++

I created a guide to using MySQL Connector/C++ for a class a while back which showed a not-too-pretty way to put data into a DB, and I created a second part using prepared statements, locking, rollbacks and all that other good stuff – then I never posted it! Well, no more ;)

MySQL Connector/C++ Guide - Part 2

Details: MySQL & Connector/C++ Introductory Guide – Part 2 of 2
Format: Powerpoint 2003 (Best readability in Powerpoint 2003 onwards, LibreOffice and OpenOffice)
Slide Count: 19

If you find anything that needs correcting feel free to let me know! Cheers!

How To: Work with MySQL and Connector/C++

I threw together a set of slides on the topic for a class which was presented today… Thought maybe they’ll be of use to someone else.

MySQL & Connector Guide

Details: MySQL & Connector/C++ Introductory Guide
Format: Powerpoint 2007 and OpenOffice Impress
Slide Count: 26

If you find anything that needs correcting feel free to let me know and I’ll make any changes as required.

Also, there’ll be a second set of slides posted soon on using prepared statements, rollbacks and enforcing transactional integrity – isn’t life fun? =P

Update: Second part now available here.

How To: Use MySQL Connector/C++ to Connect to a MySQL Database in Windows

I got this working in Linux in about ten minutes, while the same thing in Windows took me closer to three hours… The difficulty I had was that I need to get this working on multiple machines which all get wiped and reset on each boot, so it had to be entirely stand-alone with everything necessary to build in the same project. And the difficulty with that is that Connector/C++ needs the boost library to compile, which I wasn’t too keen on involving. In the end I couldn’t find a way around it and just threw the entire boost library into the same directory as the project as well as the libmysql.lib/dll and mysqlcppconn.lib libraries.

So now it works. It’s a little ugly, and the project folder comes in at 62MB, but it works. Really it’s not all that bad, if you just wanted to build and deploy something you’d end up with a couple of hundred KB executable plus a few MB of dlls. I guess I could go in and strip out some parts of the boost library which aren’t being used. But to be honest it’s been a long day and I’m sick of fighting with it, so I’ll leave that as an exercise for the reader.

Reminder / Info

  • This code is tested and working on Windows XP 32-Bit.
  • The project (i.e. download, at bottom of post) is for Microsoft Visual Studio 2008 Express
  • The version of the libs/headers included are:
    • libmysql.lib from MySQL server v1.5.36 32-Bit
    • boost library v1.45.0
    • mysqlcppconn.lib/dll from Connector/C++ v1.1.0 32-Bit
  • I really, really hate having to work with Windows.

Anyhoo – here’s the junk…

// Standard C++ includes
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
// Include the Connector/C++ headers
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/resultset.h"
#include "cppconn/statement.h"
// Link to the Connector/C++ library
#pragma comment(lib, "mysqlcppconn.lib")
// Specify our connection target and credentials
const string server   = "tcp://";
const string username = "root";
const string password = ""; // No password - thanks, WAMP Server!
int main()
	sql::Driver     *driver; // Create a pointer to a MySQL driver object
        sql::Connection *dbConn; // Create a pointer to a database connection object
        sql::Statement  *stmt;   // Create a pointer to a Statement object to hold our SQL commands
        sql::ResultSet  *res;    // Create a pointer to a ResultSet object to hold the results of any queries we run
	// Try to get a driver to use to connect to our DBMS
		driver = get_driver_instance();
	catch (sql::SQLException e)
		cout << "Could not get a database driver. Error message: " << e.what() << endl;
	// Try to connect to the DBMS server
		dbConn = driver->connect(server, username, password);
	catch (sql::SQLException e)
		cout << "Could not connect to database. Error message: " << e.what() << endl;
	stmt = dbConn->createStatement(); // Specify which connection our SQL statement should be executed on
	// Try to query the database
		stmt->execute("USE mysql");              // Select which database to use. Notice that we use "execute" to perform a command.
		res = stmt->executeQuery("show tables"); // Perform a query and get the results. Notice that we use "executeQuery" to get results back
	catch (sql::SQLException e)
		cout << "SQL error. Error message: " << e.what() << endl;
	// While there are still results (i.e. rows/records) in our result set...
	while (res->next())
		// ...get each field we want and output it to the screen
		// Note: The first field/column in our result-set is field 1 (one) and -NOT- field 0 (zero)
		// Also, if we know the name of the field then we can also get it directly by name by using:
		// res->getString("TheNameOfTheField");
		cout << res->getString(1) << endl;                
	// Clean up after ourselves
	delete res;
	delete stmt;
	delete dbConn;
	return 0;

*** REALLY IMPORTANT: Build the following project in Release mode if you want it to work!! No, really. The libs and dll’s that the project uses have been built in Release mode and you can’t mix n’ match. ***

Download of Visual Studio 2008 Express project including all necessary headers/libs/dlls (i.e. it’s ready to go – and 12MB):

Credits: Thanks to TidyTutorials for the guide that got me started.