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.

How To: Remove the ZoneAlarm Free Nag Screen

I’ve got some Windows virtual machines I use for when I need to do MS Office stuff or a brief bit of Win32 programming, and noticed earlier that each time I reboot Windows, ZoneAlarm Free decides to nag me to upgrade, and there’s no option to switch it off. In fact, I’d go as far as to say they’d gone a bit talkie-toaster… I can see why they’d do it, but I’m not going to upgrade to a full, paid security suite for a virtual machine I fire up only if and when I have to (which isn’t that often) – it’s a no-sale. So I did a bit of googling and found the solution.

The trick is that you need to modify the following registry keys and flip them from 1 to 0:

HKEY_LOCAL_MACHINE\SOFTWARE\Zone Labs\ZoneAlarm\RunSwitchbackWizard
HKEY_LOCAL_MACHINE\SOFTWARE\Zone Labs\ZoneAlarm\RunUpsellNotice

However, the problem with doing so is that Zone Alarm has these keys locked, and quiting ZoneAlarm doesn’t unlock them, so you need to reboot Windows into Safe Mode to do it by stabbing F8 during boot a few times and then selecting to boot in Safe Mode.

Once you’re in Safe Mode, you can either go and flip the flags manually using regedit, or you could dump the following into a file with a .reg extension and then execute it:

Windows Registry Editor Version 5.00

Or, you could download and run a version I created earlier (Right click and Save As…): ZA-NoNag.reg

Done & done.

Credits: Many thanks to oldsod on the ZA forums for the fix!

How To: Shrink/Compress a VirtualBox Windows Guest Machine

When you create a VirtualBox virtual-machine, you get the option to choose either a fixed sized hard drive (in which case the entire amount of space is allocated and fixed immediately), or a dynamically expanding hard drive for the virtual machines OS and file storage (i.e. you specify a maximum size for the hard drive, it starts at 0 bytes, and increases as necessary up to the maximum you gave it on creation – at which point the drive is full).

Linux and Windows via VirtualBox

This is all well and good, but the problem with dynamic storage is that although it’s more than happy to increase in size, it doesn’t come down in size again when data is removed. So, to give an example, if you created a 10GB dynamic disk for a virtual machine it starts off at 0 bytes, you install a 1GB operating system and the drive is now 1GB in size (and hence taking up 1GB of space on your actual hard drive), you rip a 4.7GB DVD to the virtual drive which makes its size now 5.7GB, you delete the DVD rip so only the OS remains – and you might think that the “dynamic” drive will automatically shrink back down to 1GB, only it doesn’t. You’re holding on to 4.7GB of unrecoverable* bloat. Lucky you… =P

You could rip another DVD and re-use that space without the drive expanding any further, but really, it’s just going to increase and increase, and you’ll know in your heart of hearts that when you’re running low on disk space you could really do with that space back to your real hard drive. In VMWare you can compact the drive image as a menu option, but in VB we have to do a three step process… So, shall we?

* = unrecoverable unless you jump through the below 3 hoops, or create a new dynamic drive image, expand it to a size just over the size of your data on your original drive, then raw-copy the data across, that is… IMHO the steps below are easier!

A-B-C, Easy As…

  1. Defrag your Windows guest machine
  2. Now we need to replace all the “blank” (but still taking up space!) areas of our drive with zeros so we can recognise them to be stripped out later. Thankfully, this is really easy. Just download free (and tiny – 47KB) command-line utility SDelete from Microsoft and run it from within your virtual Windows guest machine with the following command (the -c switch is important!):
    sdelete -c
  3. Once that’s finished running shut down your virtual machine, navigate to the folder where your virtual machine hard drive is (such as ~/.VirtualBox/HardDisks) then from your host system run the following command to compress the hard drive down to a more reasonable size:
    VBoxManage modifyhd NAME-OF-YOUR-VIRTUAL-HARD-DRIVE.vdi --compact

    So if your virtual machine name (and thus by default the hard drive name) was “XP_Client_1”, then you’d use:

    VBoxManage modifyhd XP_Client_1.vdi --compact

With that done I trimmed down an excessively bloated 25GB .VDI of Windows 7 into a still excessively bloated 15GB – but that’s just in the nature of Microsoft OS’s… =P

Update: If you get an error stating things along the lines of:

VBoxManage: error: Cannot register the hard disk 'BLAH' because a hard disk 'BLAH' with UUID {LOTS-O-HEX} already exists

then you can fix it like this:

  1. Detach the drive from your virtual machine,
  2. Edit the file ~/.VirtualBox/VirtualBox.xml and remove all lines with the drive you want to compact mentioned in the HardDrives section (Note: be careful you don’t delete the virtual machine entry itself from the MachineRegistry section! Only remove the drive from the HardDrives section.),
  3. Now you’ll be able to compact the drive, and when it’s done you can re-attach the drive to your virtual machine. Good as old! =D

Snap Happy

Another thing you can do to decrease the disk usage of VirtualBox machines is get rid of all your snapshots if you don’t need them anymore. Each snapshot is basically an entire disk image which you can roll back to, so if you have Windows 7 installed it’s about 7GB or so after a fresh install, if you then put on 500MB of patches and take another snapshot you’re storing another 7.5GB. If you then install Office or something and that takes up 2GB and take yet another snapshot you’re burning through yet another 9.5GB, so we’re up to 23.5GB already for a single 9GB drive!

You should definitely be careful when merging snapshots into the main image (basically getting rid of the snapshots), as it has the potential to break, but more likely it has the potential to confuse and cause you to throw away data you didn’t mean to. This is because of some particularly ambiguous and misleading phrasing used in VirtualBox circles – the crux of the matter being:

  • When you restore a snapshot, it will throw the current state and/or any subsequent snapshots away and leave the machine in the state defined by the snapshot you’re restoring. This can mean a lot of changes which currently exist in the image being undone, and lot of files disappear, for example – the only copy of important documents created since the snapshot you’re restoring was made. Use with care.
  • When you delete a snapshot, it will actually merge the current state of the machine into the snapshot before removing that snapshot and leaving the machine at it’s current merged state but without the snapshot existing…

Yeah, I know it’s confusing, so just be careful, okay? If you’ve got the space available just take a copy of the .VDI file from the HardDisks folder AS WELL AS a copy of the snapshots by copying the folder with the name of your VM from the Machines folder, and then merge in the snapshots – this way if it all goes nuts you can’t throw away the knackered copy and replace it with your pristine pre-merge copies.


Credits: Thanks to Damien for his article at MakeTechEasier for the initial information (you can also find out how to compress Linux guests there too, but just be aware that the technique he outlines involves cloning the drives then shrinking and re-importing them) and to Alphatek’s article for the simplification!

Winscape – Virtual Windows

How nice would it be to have the view out of your windows be, well, anything? I’d have something with the ocean in it I think. The Golden Gate bridge bit looked really nice & that’s got water, so it’d be a good start. The train journey one would prolly make me a bit nauseous though!

Where or what would you have?

How To: Stop Windows Vista/Windows 7 from Automatically Restarting Your PC after Updates

I went to clone a USB hard-drive onto another last night, and because VirtualBox USB throughput is pretty slow, and there was a couple of hundred GB to copy, I booted into Windows to do it. So far, so good. Only at some point during the night Windows decided to install some petty IE fix or some shit, and then proceeded to restart my box. Mid-clone. It probably put up a 15 minute warning saying I’m going to reboot your box unless you stop me, and then without any further input just did it.

That is just some of the most wrong-headed thinking I can possibly imagine. It’s basically saying: I don’t give a shit about anything you’re doing. I don’t care if you haven’t saved your files or you’re in the middle of something. I’m just gonna reboot. Because I want to. And I’m in charge, not you.

You can fix this default, and frankly rage-inducing, behavior as follows:

1.) Fire up the Group Policy Editor by going Start | Run | gpedit.msc

Fix Vista auto-reboot with gpedit.msc

2.) Go to: Computer Configuration | Administrative Templates | Windows Components | Windows Update and modify the No auto-restart with logged on users for scheduled automatic updates installations to Enabled

Fix Vista auto-reboot with gpedit.msc

3.) Reboot for it to take effect. (How ironic ;))

It should be noted that if you’re on a domain, domain-level settings can override group policy ones, and that after the restart window will still pop up after updating Windows – it’ll just never reboot the machine without user confirmation that it’s okay to do so.

Oh, and if you’re on Vista Home Edition, you don’t even get group policy tools in the first place, in which case you can get busy with the registry as per this article – or use the registry file they provide, or just use this Auto Reboot Remover tool.