Friday, October 9, 2009

How to connect to mysql using C/C++

Pre-requisites


-gcc must be installed
-mysql-dev must be installed


Procedure
-Create a user with access to the database/table you need to access


grant all privileges on test.* to test identified by 'mypassword';


-Create a table and populate it:


CREATE TABLE `mytable` (
  `id` int(11) NOT NULL DEFAULT '0',
  `name` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
)



insert into mytable values (1,'Luis');
insert into mytable values (2,'Scott');
insert into mytable values (3,'Rob');


-Write the C program: 



#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>


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


   char *server = "127.0.0.1";
   char *user = "test";
   char *password = "mypassword";
   char *database = "test";
   char query[] = "select * from mytable";
   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));
      exit(0);
    }


   /* Execute the query */
   if (mysql_query(conn, query)) {
       fprintf(stderr, "%s\n", mysql_error(conn));
       exit(0);
   }


   /* send SQL query */
   res = mysql_use_result(conn);


   /* output fields 1 and 2 of each row */
   while ((row = mysql_fetch_row(res)) != NULL)
      printf("%s %s \n", row[0],row[1]);


   /* Release memory used to store results and close connection */
   mysql_free_result(res);
   mysql_close(conn);
}


-Compile it
$ gcc -c `mysql_config --cflags` mysql_connection.c
$ gcc -o mysql_connection  mysql_connection.o `mysql_config --libs`


-Run it


$ ./mysql_connection
1 Luis
2 Scott
3 Rob

No comments:

Post a Comment