O'Reilly logo

MySQL in a Nutshell 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 perform use the C API.

Connecting to MySQL

When writing a C program to interact with MySQL, first make a connection to MySQL. To do this easily, you need to include a couple of C header files: 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 of the < and > symbols surrounding stdio.h, 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, with the aide of double quotes, the absolute path is given. An alternative here would have been <mysql/mysql.h>, because the header file is in a subdirectory of the default directory.

Within the standard main function just shown, the connection to MySQL is established. The first line sets up the definition for MySQL, with mysql, which will be referenced by mysql later. The second line defines and names a results set based on the definitions for MYSQL_RES in mysql.h. The results are to be stored in the result array, which will be an array of rows from MySQL. The third line of main uses the definition for MYSQL_ROW to establish the row

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