Connecting to MySQL in C

MySQL comes with a library to make talking to MySQL with C easyish. There are a few things you have to install first, though. I’m using Ubuntu 8.04 for this walkthrough, but things should be similar for other flavours of Linux.

Before we start, we have to download the development files required:

sudo apt-get install libmysqlclient15-dev

Without all of these files, you will probably get errors like:
error: mysql.h: No such file or directory

Once that’s done, you’re ready to go. I won’t go through all of the nitty gritty details about data types and stuff – if you want more info, go to the MySQL website and look it up.

Below is a demo program which reads in an SQL statement, executes it and prints out the results.




int main()
MYSQL conn; / MySQL connection */
MYSQL_RES *result; /* result set / MYSQL_ROW row; / an instance of a row from the result */

int x;

/* connection details */
char *server = “localhost”;
char *user = “username”;
char *password = “password”;
char *database = “information_schema”;

/* attempt to connecto to the server */
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
return 0 ;

char query[1000];

printf(“Query: “);
fgets(query, 1000, stdin);

/* run the SQL query */
if (mysql_query(conn, query)) {
return 0;

result = mysql_use_result(conn);

printf(“| RESULT |\n”);

/* print out the results */
while ((row = mysql_fetch_row(result)) != NULL) {
printf(“| %s”, row[0]);

/* layout */
for(x = strlen(row[0]); x < 21; x++)
printf(” “);



/* clean up */

return 0;

To compile this program, save the code into mysql.c run the following:

gcc -I/usr/include/mysql mysql.c -lmysqlclient -o mysql -Wall

Leave a Reply

Your email address will not be published.