How To: Use MySQL Connector/C++ to Connect to a MySQL Database in Windows
r3dux | November 27, 2010I 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://127.0.0.1:3306"; 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 try { driver = get_driver_instance(); } catch (sql::SQLException e) { cout << "Could not get a database driver. Error message: " << e.what() << endl; system("pause"); exit(1); } // Try to connect to the DBMS server try { dbConn = driver->connect(server, username, password); } catch (sql::SQLException e) { cout << "Could not connect to database. Error message: " << e.what() << endl; system("pause"); exit(1); } stmt = dbConn->createStatement(); // Specify which connection our SQL statement should be executed on // Try to query the database try { 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; system("pause"); exit(1); } // 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; system("pause"); 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): MySQL-Connector-Test.zip
Credits: Thanks to TidyTutorials for the guide that got me started.











yeah windows is a right pain to do anything even if we had access to cygwin or vmware at uni it would be easier i hate how something works perfectly on linux and you get it on windows and its like argh my head hurts already
hi, I am stuck at the try to query the database step. The message error is unknown exception. Can you help me to solve it? Thank you very much.
Hi Chloe,
I assume the project compiles. If you have WAMP server installed, it’s probably worth doing some or all of the following:
- Confirm the mysql service is running from the WAMP indicator in the bottom-right system tray,
- Confirm (via phpmyadmin) that a database called “mysql” exists. Phpmyadmin is accessible by going to http://localhost in a web browser while all WAMP server services are running,
- Confirm that you can log into mysql using mysqladmin -u root (the mysqladmin.exe utility will be in C:\wamp\bin\mysqlx.y.z\mysql or such) so that you know it’s not a username/password issue,
- Try turning your firewall off to make sure it’s not blocking traffic on port 3306
Put some debug output in the code if you’re not sure where it’s failing. But if I understand you correctly, the query database block is running, but generating an exception so you see output of: “SQL error. Error message: unknown exception”, right? As long as you can use mysql.exe command line util (found in the same place as the mysqladmin on mentioned above), and the commands use mysql; followed by show tables; actually show you a list of tables in the database then we can rule out that MySQL isn’t functioning at all.
Have a go and let me know how you go on – and remember, the more info you give me to work with the better I’m likely to be able to help you! If there are error messages, please provide the exact and complete error messages.
Also, some further reading: Introduction to MySQL
Cheers!
Thank you very much. =D
It works now. May I know how to select and print out the information inside one table? Sorry for the trouble.
Its ok… i already solve it! =D thank you!!!!!!!!
Hi,
Sorry to bother you again. I cant seem to add the insert data into database part into my code.
There is always a red color line under template regardless of where I tried to put #include . Can you help me solve this? Thank you.
Edited for brevity by r3dux – 2011-04-14
That code looks awfully familiar
Ah, I see what you’re getting at – you’ve got the templated toString function all messed up. Also, the way I did it in the slides (i.e. the way you did it) isn’t a particularly nice way of creating SQL queries.
I’ve done a better way of inserting data using prepared queries and other such stuff in another slide set, I just haven’t posted it – I’ll clean up the slides and post tomorrow & you’ll be all set.
If you want to have a go yourself before then, the templated toString function should look like this:
And to use it, you’ll need to include the following:
Here’s some example code to demonstrate how the toString function works:
As promised, second part is now up here and shows how to use prepared statements to insert data – I think you’ll find it a much nicer method =D
Cheers!
-r3dux
Thank you sooo much… everything can run smoothly now.. =D
hi,
may i know how to link c++ window form application using button with mysql?
like when i press the button in the form, it will link to mysql.
so i can proceed with add/delete/update to mysql.
thanks in advance.
Hi Michael,
Sorry, but I have no idea (I don’t really code GUIs in Windows) but this looks like it’ll show you how to trigger functions from buttons in a Windows form: http://msdn.microsoft.com/en-us/library/s0scsyfb.aspx
It sounds like a pretty common thing people would want to do, so I’m sure there’s plenty of tutorials/video guides out there. Have a look around & give it a go. If you really can’t get it I’ll have a look and try to knock a simple “call-a-function-when-you-press-a-button” example together for you, but Windows programming is definitely not my forte, k?
Best wishes,
r3dux
Hi, Im currently having some probs with mysql. im using vs2010 and wamp, yet i have problem whenever i debug:
Could not connect to database. Error message: Unknown exception.
Do you know the solution to it?
Um, maybe. You cannot build the provided project in Debug mode, you have to build it in Release mode, because there are no debug symbols in the provided libraries, as mentioned in the article. If you want to build it in debug mode, you need to obtain and link to debug versions of the the libraries (libmysql, Connector/C++ etc).
If you are building in Release mode and it’s still not working, then I’m not so sure. The connect to server catch block is triggering, i.e. this bit:
But, I’ve just tested the code with Visual Studio 2008 and I get:
Could not connect to database. Error message: Can’t connect to MySQL server on ’127.0.0.1′ (10061) – if the MySQL server isn’t running or is pointed at an bad address,
SQL error. Error message: Access denied for user ”@’localhost’ to database ‘mysql’ – if MySQL is running and we connect to it, but provide an invalid username, and
Could not connect to database. Error message: Access denied for user ‘root’@'localhost’ (using password: YES) – if MySQL is running and we connect but provide an invalid password.
Again, I think it’ll be a library thing and either an incompatibility with VS2010 (in which case perhaps you’ll need to get libraries compiled for VS2010), or you’re trying to run 32-bit libs on a 64-bit OS and it’s not liking it.
Best of luck & hope you get it sorted,
r3dux
I’m getting the same error as Chloe. Did you find out what was causing her problem?
I followed your suggestions to her:
– Confirm the mysql service is running from the WAMP indicator in the bottom-right system tray,
– Confirm (via phpmyadmin) that a database called “mysql” exists.
– Can log in using “msql.exe -u root”, & issue “use mysql” & “show tables”
– Turned firewall off
I put some debug messages and it looks like the error happens when doing:
stmt->execute(“USE mysql”);
Everything compiled ok under MS VC++ 2010 Express (Release build).
I was going to try w/ 2008, but having trouble downloading it at the moment.
Would appreciate any help.
Thanks.
Hi James,
It sounds like you’re doing everything right – service is running, can see & connect to database from MySQL tools etc….
If you’re getting an unknown exception error (which I think is the error you’re referring to) then I’d have to guess that it’s got to be some kind of library mismatch – try getting a new version of Connector/C++ for Visual Studio 2010 and substitute in those dlls for any in the existing project. Also, the libs I provided with the precompiled project are 32-bit, if your system is 64-bit it’s not going to work.
Also if you separate out each line of “risky” code into its own separate try/catch block then you’ll know exactly which statement is failing, like this:
I think you’re right about needing to recompile Connector/C++ under VS 2010.
Was able to obtain VS 2008 Express and it works fine now.
Thanks for the help & the great sample code!
It’s a bit strange for me.
In my case, it only works with DEBUG mode.
In RELEASE mode, it spit out message like “Could not connect to database. Error message: Unknown exception”.
I tested with: Windows 7 SP1 Pro x64 + MySQL x64 5.5.12 + VS 2010 SP1
(I converted the original project into VS 2011 project)
To run it in RELEASE model, I had to replace “mysqlcppconn.dll” and “mysqlcppconn.lib”.
(I extracted the files from “mysql-connector-c++-noinstall-1.1.0-win32.zip” at http://www.mologie.de/blog/2010/10/mysql-connector-c-und-visual-studio-2010/)
Did I do something wrong?
If I try to run it again in DEBUG mode after I replace the files (to run it in RELEASE mode and it works),
then it spit out message like “Could not connect to database. Error message: Access denied for user ‘ODBC’@'localhost’ (using password: NO)”
I don’t know what is wrong with me.
Any advice will be appreciated.
Thanks.
I originally wrote this code using XP and Visual Studio 2008 and it worked correctly when built in Release mode – if you’re going to use this with Windows 7 and/or Visual Studio I’d recommend creating a new project entirely and copying and pasting the code in then setting up the libraries of the VS project, as something’s obviously going wrong with the conversion.
I recently had to cover this material in a class I’m teaching (like, last week) and it worked fine with Windows 7 and Visual Studio 2008 – so it must be a VS2010 thing.
This might help you out (but remember to get rid of the password if you’re using WAMP Server as by default there is no password for the root account): http://blog.ulf-wendel.de/?p=215#hello
Hi r3dux,
i tried to connect mysql db using c++. but, compile time i get no input file from compiler.how to solve this problem?
I don’t know what you mean by “no input file from the compiler” – what error message do you get? (please quote the entire, exact error message)
How can I specify connection parameters when creating a connection?
For instance, I want to set the parameter “CharSet” to “utf8″.
I’m used to appending all the key / value pairs after the port in the url, but that doesn’t seem to work.
Thanks,
Paul
That’s a good question – unfortunately I’ve no idea… I took a look through this http://dev.mysql.com/doc/refman/5.6/en/connector-cpp.html and couldn’t find much in the way of answers either.
Your best bet might be to just make sure the database and tables are using UTF-8 encoding and try your luck with some extended (i.e. non-ASCII) characters.
Sorry I can’t be of more help!
Hi. Thank you before nothing.
I’m working with Windows 7 and Visual Studio 2010. I have the same problem that was writen by “rr.” user.
I try connect to mysq data through c++ code. When I compile it in DEGUB mode, it works successfully, but I need compile my proyect with RELEASE mode. In this case always has an error to connect to dabase:
” dbConn = driver->connect(current_server, current_username, current_password); ”
Error:
“Could not connect to database. Error message: Unknown exception”.
I have tried with:
MySQL Connector/C++ 1.1.1 (and boost_1_52 for this case to be neccesary)
MySQL Connector/C++ 1.0.5
Thanks in advance.
I wish I knew how to help you – I’ve had nothing but headaches from trying to use MySQL Connector C++ with various versions of Visual Studio, Boost and compiling in Debug and Release mode. On one machine it’ll work fine, then on another it won’t work in one build mode but will in another, and on a different machine again it’ll work in the opposite mode (say, Debug) but not in Release!
It (MySQL Connector C++) just seems to be problematic and poorly maintained piece of code all round.
Maybe this guy can help?:
http://pixelstech.net/article/1338576740_Using_MySQL_Connector_C%2B%2B_with_Visual_Studio_2010
Best of luck with it and sorry I couldn’t be of more help.
Thank you to reply me so fast.
I’m going to to look for to fix this problem.
Thank you so much.