Pages

Checking a connection to MySQL

Let's write a minimal program that just try to connect to a MySQL server.

The assumption is that we are working in C++ for MS-Windows and we are using the MySQL connector/C as API to connecting to the database.

It is a very simple piece of code but, since we are using a C library it happens to be quite verbose and requires us to be acquainted with a type, MYSQL, and a few functions.

mysql_init()

The MYSQL type is actually a typedef for the st_mysql structure. In any case, it is a collection of data related with the database connection.

First thing we have to do is calling mysql_init(), that (allocates room and) initializes a MYSQL object in a way that we could use it to open a MySQL connection. If we pass to it a NULL pointer, it allocates a new MYSQL object before initializing it, otherwise it uses the one we provide it.

The return value is the pointer to the MYSQL object, or NULL in case of error.

mysql_options()

This function is used to change many different connection setting on the initialized MYSQL object. Currently we don't need to do anything like that, so just remember this useful piece of information for another time.

mysql_real_connect()

To connect to the database we could use the mysql_connect() function, but it is deprecated, so we just forget about it and call mysql_real_connect().

Besides an initialized MYSQL object, we need the name of the host the database sits on (NULL means "localhost"), the user name, password, database name (could be left NULL, if set, determines the default database name for the connection), port (used in case of TCP/IP connection, if we give a 0, the MySQL default 3306 will be used), unix socket number (for socket or pipe connection), and client flags.

It returns NULL in case of error.

mysql_error()

When we see a mysql_* function returns an error we can get a human readable description of it calling mysql_error() for the current MYSQL object.

mysql_close

At the end of the day, we should cleanup the connection, and this is done by mysql_close().

As we can see in the example below, it is faster to write the code:

#include <iostream>
#include "my_global.h" // this is required when working for MS-Windows
#include "mysql.h"

using std::cout;
using std::endl;

void ms01()
{
cout << "Opening a connection to mysql" << endl;
MYSQL mysql; // we allocate the memory for the object, putting it on the stack

if(mysql_init(&mysql) == 0)
{
cout << "Can't initialize mysql object" << endl;
return;
}

// first 0 is for localhost, se use the default port, and specify no database
if(mysql_real_connect(&mysql, 0, "root", "password", 0, 0, 0, 0) == 0)
{
cout << "Connection failed: " << mysql_error(&mysql) << endl;
return;
}

mysql_close(&mysql);
cout << "Connection to mysql opened correctly" << endl;
}

No comments:

Post a Comment