Monday, January 23, 2012

A resource for the mysql needful

Hey everyone.

I recently had a task given by a ivy league company for its recruitment assessment. The program was to be done on c++, and needed the use of MySql C API. It took me a lot of time to understand how it worked. I tried a lot of googling, but it did not help out much. It was only by chance wen one of my friends suggested a page which eventually leads me to the API description page. Things went smooth from there.

I've decided to share te program with everyone, for education purposes only. Do not send this program to the recruiter. Read it, observe it, understand it, and use your logic. Also, should i mention, the program has been compiled and checked for any errors(no errors found), but hasn't been tried on a database. Mysql doesn't install properly on my Ubuntu 10.10(wonder whats the problem).


Write a program in C to read a single line mysql query from a text file, and execute it.


#include
#include
#include
main() {
MYSQL *conn; /*pointer to connect handler */
MYSQL_RES *res ;/*shows result of the query */
MYSQL_ROW row; /*one row of data*/
char *server = "localhost";
char *user = "root";
char *password = "1"; /* set me first */
char *database = "mysql";
conn = mysql_init(NULL);
char ch[100]; /*string to get sql command from file*/
int colno;



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

/* to get sql command from file */
FILE *fin;
if(fin==NULL)
{
printf("no command file");
}
fin=fopen("sqlcomm.txt","r");
fgets(ch,100,fin);




/* send SQL query */
if (mysql_query(conn, ch)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_use_result(conn);//read the result of the query, one word at a time

colno=mysql_field_count(conn);


/* output table name */
printf("The Output for your query is:\n");
int c=0;

while ((row = mysql_fetch_row(res)) != NULL)
{ for(c=0;c<=colno;c++)
printf("%s \n", row[c]);}




/* close connection */
mysql_free_result(res);
mysql_close(conn);
/* close the file */
fclose(fin);
}



I've added comments too to make understanding easier. Special thanks to my old pal Shashank Mehra for his inputs, and for clearing out silly mistakes.

No comments: