Using C with MySQL

This section presents the basic tasks you need to use the C API.

Connecting to MySQL

When writing a C program to interact with MySQL, you first need to prepare variables that will store data necessary for a MySQL connection and query results, and then you need to establish a connection to MySQL. To do this easily, you need to include a couple of C header files (as shown in the code example): stdio.h for basic C functions and variables, and mysql.h for special MySQL functions and definitions. These two files come with C and MySQL, respectively; you shouldn’t have to download them from the Web if both were installed properly:

   #include <stdio.h>
   #include "/usr/include/mysql/mysql.h"
   int main(int argc, char *argv[  ])
           MYSQL *mysql;
           MYSQL_RES *result;
           MYSQL_ROW row;

Because stdio.h is surrounded by < and > symbols, C is instructed to look for it in the default location for C header files (e.g., /usr/include), or in the user’s path. Because mysql.h may not be in the default locations, the absolute path is given with the aid of double quotes. An alternative here would be <mysql/mysql.h> because the header file is in a subdirectory of the default directory.

Within the standard main function just shown, variables needed for the connection to MySQL are prepared. The first line creates a pointer to the MYSQL structure stored in the mysql variable. The next line defines and names a results set based on the definitions for MYSQL_RES in mysql.h. The results are stored in the ...

Get MySQL in a Nutshell, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.