O'Reilly logo

MySQL in a Nutshell, 2nd Edition by Russell J.T. Dyer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required