C program to get the column names of the MySQL data table in Linux

Here, we are going to write a C program to get the column names of the MySQL data table in Linux.
By Nidhi Last updated : March 10, 2024

Prerequisites

The following packages need to be installed in the ubuntu machine for MySQL connectivity using the C program.

sudo apt install default-libmysqlclient-dev

Problem Solution

In this program, we will connect to the MyDb database, and then we will retrieve the column names of the "employee" table and print the result on the console screen.

Program/Source Code

The source code to get the column names of the MySql data table in Linux is given below. The given program is compiled and executed successfully on Ubuntu 20.04.

//C program to create a retrive records from 
//MySQL database table in Linux.

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

int main()
{
    char server[16] = "localhost";
    char username[16] = "root";
    char password[16] = "root";
    char database[16] = "MyDb";

    MYSQL* conn = mysql_init(NULL);
    MYSQL_FIELD* column;
    MYSQL_ROW* row;

    if (conn == NULL) {
        printf("MySQL initialization failed");
        return 1;
    }

    if (mysql_real_connect(conn, server, username, password, database, 0, NULL, 0) == NULL) {
        printf("Unable to connect with MySQL server\n");
        mysql_close(conn);
        return 1;
    }

    if (mysql_query(conn, "SELECT * FROM Employee")) {
        printf("Unable to connect with MySQL server\n");
        mysql_close(conn);
        return 1;
    }

    MYSQL_RES* rs = mysql_store_result(conn);

    if (rs == NULL) {
        printf("Unable to compile SQL statement\n");
        mysql_close(conn);
        return 1;
    }

    if ((row = mysql_fetch_row(rs))) {
        while (column = mysql_fetch_field(rs)) {
            printf("%s ", column->name);
        }
        printf("\n");
    }

    mysql_close(conn);

    return 0;
}

Output

$ gcc column_name.c -o column_name  `mysql_config --cflags --libs`
$ sudo ./column_name 
Eid Ename Salary

In the above program, we included the mysql.h header file to use MySql connectivity related functions. Here, we created variables server, username, password, and database that are initialized values specific to the MySQL connectivity.

Here, we connected to the MyDb database in the MySql server using the mysql_real_connect() function and then we retrieved the name columns using mysql_fetch_row() and mysql_fetch_field() functions and then print the result on the console screen.

C MySQL Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.