By Bryan Young
Expert Author
Article Date: 2010-06-17
Many languages include the ability to connect to a database and utilize the information stored within. For those that don't have these abilities automatically, there are different varieties of MySQL connectors available for installation. The version for C is the connector/C. Once the connector/C is installed (instructions on how to do this can be found here), you can add a connection to a mysql database to any C program with ease.
Below I will outline a simple program to connect to the "databasename" database. This database has one table "user" with three columns, "id", "name" and "department".First, of course, you must inlcude the mysql.h file in your header, along with a few standard files.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <mysql.h>
Next, we open our main function and initialize variables. The data types shown here are all included in the mysql connector pack. MYSQL is the connection to the database, MYSQL_RES is the result set returned from a query, and MYSQL_ROW is a specified row from the result set.
int main(int argc, char* argv[]) {
MYSQL *conn;
MYSQL_RES *result;
MYSQL_ROW row;
The next step is to open the connection to the database. The mysql_init() function returns an empty database connection, which is filled by mysql_real_connection(). "localhost" can be replaced with a server address if you are using a remote mySQL server. At each step, we have an error catch which outputs the given error values and ends the program in the event of a failure.
conn = mysql_init(NULL);
if (conn == NULL)
{
printf("Error %d: %s", mysql_errno(conn), mysql_error(conn));
exit(1);
}
if (mysql_real_connect(conn, "localhost", "user", "password", "databasename", 0, NULL, 0) == NULL)
{
printf("Error %d: %s", mysql_errno(conn), mysql_error(conn));
exit(1);
}
Now we can query the database using this function, mysql_query(). While a select statement is being shown below, this same function can be used for inserts, deletes, updates, and any other valid query. Again, there is an error catch for malformed queries or connection problems.
if (mysql_query(conn, "SELECT * FROM user"))
{
printf("Error %d: %s", mysql_errno(conn), mysql_error(conn));
return NULL;
}
All that is left to do is process the data received using nested loops. The mysql_fetch_row() function returns each row from the result set in turn, and the mysql_num_fields function returns the number of columns in each row.
while ((row = mysql_fetch_row(result)) != NULL)
{
int i;
for(i=0;i
printf("%s ",row[i]);
printf("n");
}
Now we simply close the database and end the program.
mysql_close(conn);
return 0;
}