The Connection

An application should call mysql_init( ) before performing any other operation. This method initializes a database handler used by many of the functions—including the connection and error handling functions. In the above example, we created a handler in the declaration:

MYSQL *connection, mysql;

The pointer to the handler, connection, will represent our actual connection once it is made; the allocated handler, mysql, represents a null connection until we actually make the database connection. Our first step is to initialize this handler through the mysql_init( ) function:

mysql_init(&mysql);

This function takes a reference to an allocated null handler. The MySQL API requires this hocus-pocus with a null handler to support operations such as error handling that occur outside the context of a physical database connection. The first function needing this handler is the actual connection API: mysql_real_connect( ).

Tip

At first glance over the API list, you may be tempted to use the mysql_connect( ) function. The odd name of the mysql_real_connect( ) function exists because it is a replacement for the long-deprecated mysql_connect( ) function. The old mysql_connect( ) provided compatibility for mSQL applications; you should never use it in modern applications.

The mysql_real_connect( ) function takes several arguments:

null handler

The connection handler allocated and subsequently initialized through mysql_init( ).

host

The name of the machine on which the MySQL server is running.

user

The user ID of the MySQL user to connect under.

password

The password that identifies the user you are connecting under.

database

The name of the database on the MySQL server to connect to.

port

The port number MySQL is listening to. If you specify 0, it will connect to MySQL on MySQL’s default port number.

unix socket

A pointer to the Unix socket or null. Under Windows, you should be certain to pass in NULL and not a null string—i.e., use (char *)NULL and not (char *)"".

client flag

A number including a set of flags for the connection. You will generally pass in 0 here.

Upon success, the mysql_real_connect( ) function returns a pointer to an actual MySQL connection. To verify success, your application should check for a null value:

if( connection == NULL ) {
    /* An error! */
}

If you run into an error during a connection, it becomes clear why you needed that null handler we created in mysql_init( ). It provides you with access to the error:

printf("%s
", mysql_error(&mysql));

We will go into more detail on error handling later in the chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset