Connecting to Your Database

Connecting to a MySQL database has two stages. First you initialize a connection handler; then you connect to the MySQL server. In the second step, you can optionally specify which database to use. Let's look at this procedure in detail.

You first need to call mysql_init() to initialize a connection handler. Its syntax is

*mysql_init (*mysql)

where *mysql is a database connection handle, although typically we pass it NULL to initiate a new connection. The result is an initialized MYSQL* handle.

We'll embed this function into common.c, which holds our common functions. The relevant lines within the function look like this:

 MYSQL *mysql; if ((mysql = mysql_init (NULL)) == NULL) { fprintf (stderr, "mysql_init() failed.\n"); ...

Get Sams Teach Yourself MySQL in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.