Connecting to a mysql database from C is a fairly straightforward process. The following instructions should work on any Linux distro or UNIX computer.
1 |
|
How do I compile and link program against MySQL libs?
MySQL comes with a script called mysql_config. It provides useful information for compiling your MySQL client and connecting it to a MySQL database server. You need to use following two options.
Pass the libs option i.e. ‘Libraries’ to show required Libraries to link with the MySQL client library.
1 | $ mysql_config --libs |
Output:
1 | -L/usr/local/Cellar/mysql/8.0.13/lib -lmysqlclient -lssl -lcrypto |
Pass cflags option ‘Compiler flags’ to find include files and critical compiler flags and defines used when compiling the libmysqlclient library.
1 | $ mysql_config --cflags |
Output:
1 | -I/usr/local/Cellar/mysql/8.0.13/include/mysql |
You need to pass above two options to your compiler. So to compile above program, enter:
1 | $ gcc $(mysql_config --cflags) mysql.c $(mysql_config --libs) |
Now execute program:
1 | $ ./a.out |
Output:
1 | MySQL Tables in mysql database: |
You have successfully connected to and retrieved information from your MySQL database from within a C environment.