Implementing database into C program
After completing basic C programming, it is exciting to write some more complex or more functional programs. With more functionality added there is a need for the database for which MySQL plays an important role.
STEP 1 :
First step is to install mysql server
Enter following commands in terminal :
sudo apt-get install mysql-server
sudo apt-get install libmysqlclient-dev
now MySQL server is installed.
STEP 2:
Now we have to create database in mysql.
now MySQL monitor will open
STEP 1 :
First step is to install mysql server
Enter following commands in terminal :
sudo apt-get install mysql-server
sudo apt-get install libmysqlclient-dev
now MySQL server is installed.
STEP 2:
Now we have to create database in mysql.
- Open terminal and Enter command : sudo mysql -u root -p
now MySQL monitor will open
- create database using command : CREATE DATABASE emp_data;
- To use created database use command : USE emp_data;
- Create table using command : CREATE TABLE emp(id int(4) not null,name text not null,age int(3) not null);
- To enter data in table we can use INSERT command : INSERT INTO emp(id,name,age) VALUES(1,'emp_1',45);
Now we had successfully created our database.STEP 3:Now we have to write program in c using MySQL C api to connect to database and to access data present in databaseThe program will be :#include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>
#include <string.h>
static char *host = "localhost"; //host
static char *user = "root";//username
static char *pass = "password";//password of the database
static char *dbname = "emp_data";//name of the database
unsigned int port = 3306;
static char *unix_socket = NULL;
unsigned int flag = 0;
int main(){
MYSQL *conn = mysql_init(NULL);//This structure represents handler for one database connection
MYSQL_RES *res;//This structure represents the result of a query
MYSQL_ROW row;//This is a type-safe representation of one row of data
if(!mysql_real_connect(conn,host, user, pass, dbname, port, unix_socket, flag)){
//this function attempts to establish a connection to a MySQL database engine running on host
fprintf(stderr, "\nError : %s [%d]\n",mysql_error(conn),mysql_errno(conn));
exit(1);
}
char *query = "SELECT * FROM emp";
mysql_real_query(conn,query,strlen(query));//executes the SQL statement(query)
printf("Connection successful...!\n\n");
res = mysql_store_result(conn);//to store result of query into MYSQL_RES structure
while(row = mysql_fetch_row(res)){//The number of values in the row is given by this function
printf("%s\t%s\t%s\n",row[0],row[1],row[2]);//row[0],row[1],row[2] for id,name,age respectively
}
mysql_free_result(res);
mysql_close(conn);
mysql_library_end();
return EXIT_SUCCESS;
}STEP 3:To compile program : gcc mysql.c -o file $(mysql_config --cflags --libs)In this way we can use MySQL C API to use databases(we can also do insertion and deleting from database by changing query passed to mysql_real_query())
Comments
Post a Comment