Sunday, April 14, 2013

MySQL Database In C Programming

Hi guys..In this post i am going to show you, how to use MySQL databases in C programs.

Installing MySQL on Debian based Linux:

To install MySQL, run the following command in terminal:
#sudo apt-get install mysql-server

During the installation, you will be prompted to enter a password for the MySQL root user. After that, install MySQL  client using following command.
#sudo apt-get install libmysqlclient-dev

To log into MySQL use following command. It will ask you to enter root password
#mysql -u root -p


To see existing databases use the following command
#mysql> show databases;

To exit from MySQL use following command
#mysql> exit


Using MySQL in C:

Now lets write a C program in which we create a MySQL employee database, and insert few records.

//FileName: MySQLinC.c

 #include <my_global.h>
#include <mysql.h>
#include <stdio.h>

int main(int argc, char **argv)
{

  MYSQL *conn;
  // initializing mysql connection
  conn = mysql_init(NULL);

  if (conn == NULL) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }
  // connecting to mysql server
  if (mysql_real_connect(conn, "localhost", "root",
          "rootpassword", NULL, 0, NULL, 0) == NULL) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }
 // creating employeedb
  if (mysql_query(conn, "create database employeedb")) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }

 // closing MySQL Coneection
    mysql_close(conn);

 // again initializing mysql connection
  conn = mysql_init(NULL);

  if (conn == NULL) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }
  // connecting to employeedb in mysql server
  if (mysql_real_connect(conn, "localhost", "root",
          "rootpassword", "employeedb", 0, NULL, 0) == NULL) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }
 // creating employee table
 mysql_query(conn, "CREATE TABLE employee(name VARCHAR(25))");

 // inserting records in employee table
  mysql_query(conn, "INSERT INTO employee VALUES('Sagun Baijal')");
  mysql_query(conn, "INSERT INTO employee VALUES('Leena Chouray')");
  mysql_query(conn, "INSERT INTO employee VALUES('D.V Bhat')");
  mysql_query(conn, "INSERT INTO employee VALUES('Reniguntla Sambaiah')");
  mysql_query(conn, "INSERT INTO employee VALUES('Shivnath Kumar')");

 // closing MySQL Coneection
  mysql_close(conn);
}

To Run: gcc MySQLinC.c -o MySQLinC  `mysql_config --cflags --libs`
             ./MySQLinC

To check the emploeedb is created or not use following commands at command line

# mysql -u root -p
#mysql> show databases;
#mysql> use employeedb;
#mysql> show tables;
#mysql> select * from employee;





No comments:

Post a Comment