top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Is it possible to connect MySQL database with c code, if yes then how?

0 votes

Is it possible to connect database with c code, if yes then how?

If possible share the sample code for connecting to a MySQL database and run a sample query....

posted May 24, 2017 by Pooja Singh

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
Best answer

The answer is definitely yes. An example for connecting to MySQL with C is below:

 #include <mysql.h>
 #include <stdio.h>
     MYSQL *conn;
     MYSQL_RES *res;
     MYSQL_ROW row;
     char *server = "localhost";
     char *user = "root";
     char *password = "PASSWORD";  /* set me first */
     char *database = "mysql";
     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));
     /* send SQL query */
     if (mysql_query(conn, "show tables")) 
        fprintf(stderr, "%s\n", mysql_error(conn));
     res = mysql_use_result(conn);
     /* output table name */
     printf("MySQL Tables in mysql database:\n");
     while ((row = mysql_fetch_row(res)) != NULL)
     printf("%s \n", row[0]);
     /* close connection */
answer May 25, 2017 by Naziya Raza Khan