MySQL – C code example

[adsense id=”0514458240″ width=”468″ height=”60″]

Here is sample C code connecting to a MySQL server, executing a SQL command and returning the contents. In addition to this I also provide the compilation flags required as well as a Makefile simplifying the compilation process.

#include 
#include 

int main() {
	MYSQL *conn;
	MYSQL_RES *res;
	MYSQL_ROW row;

	char *server = "localhost";
	char *user = "root";
	char *password = "test";
	char *database = "demo";
	int len;
	char ch;

	conn = mysql_init(NULL);

	/* Connect to database */
	if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
		fprintf(stderr, "%s\n", mysql_error(conn));
		return 1;
	}

	/* send SQL query */
	if (mysql_query(conn, "SELECT name FROM testimport")) {
		fprintf(stderr, "%s\n", mysql_error(conn));
		return 1;
	}
	

	res = mysql_use_result(conn);

	/* output table name */
	printf("Returning list of names:\n");
	while ((row = mysql_fetch_row(res)) != NULL)
		printf("%s \n", row[0]);

	/* close connection */
	mysql_free_result(res);
	mysql_close(conn);
}

Compiling with just the gcc command will fail:

$ gcc main.c -o main
main.c:2:19: error: mysql.h: No such file or directory
main.c: In function ‘main’:
main.c:6: error: ‘MYSQL’ undeclared (first use in this function)
main.c:6: error: (Each undeclared identifier is reported only once
main.c:6: error: for each function it appears in.)
main.c:6: error: ‘conn’ undeclared (first use in this function)
main.c:7: error: ‘MYSQL_RES’ undeclared (first use in this function)
main.c:7: error: ‘res’ undeclared (first use in this function)
main.c:8: error: ‘MYSQL_ROW’ undeclared (first use in this function)
main.c:8: error: expected ‘;’ before ‘row’
main.c:36: error: ‘row’ undeclared (first use in this function)

This needs to be compiled in a particular way:

gcc main.c -o main `mysql_config --cflags --libs`

Alternatively you can create a Makefile with the following contents:

project: main
main: main.c
	gcc main.c -o main `mysql_config --cflags --libs`

In order to compile simply type in the command “make”

$ make
gcc main.c -o main `mysql_config --cflags --libs`

[googleplus]