Database and C

The Following Program is Compiled in Fedora 8.

1. To Compile C code with mysql use the follwing command.

2. This is for Database connectivity of C with mysql (dbtest.c). This will find the database if a table exist or not if not then create the table in the database.

gcc -o dbtest $(mysql_config --cflags) dbtest.c $(mysql_config --libs)

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <sys/types.h>

#include <sys/param.h>

#include <sys/stat.h>

#include </usr/include/unistd.h>

#include "/usr/include/mysql/mysql.h"

main()

{

MYSQL *conn;

MYSQL_RES *res = NULL;

MYSQL_ROW row;

char *server="localhost";

char *user = "root";

char *password ="admin";

char *database = "test";

char query[100]="Select * from emp";

conn = mysql_init(NULL);

if (!mysql_real_connect(conn, server,user, password, database, 0, NULL, 0))

{

printf("Problem in Connecting To Database.......%s\n",database);

if(conn)

mysql_close(conn);

printf("Connection closed");

}

else

{

printf("\nDatabase Connected. Now Looking For Emp Table\n");

if(!mysql_query(conn,query))

{

printf("\nTable Exist in Database\n");

if(conn)

mysql_close(conn);

}else {

printf("\nTable Doesn't Exist\n");

strcpy(query,"create table emp(name varchar(20))");

if(!mysql_query(conn,query))

{

printf("\nTable Created\n");

if(conn)

mysql_close(conn);

}else

{

printf("\nError in Executing Query\n");

if(conn)

mysql_close(conn);

}

}

}

}

/////////////////////////////////////////////////////////////////////////////////////////////