Q:

C program to create a table in MySQL database dynamically in Linux

0

C program to create a table in MySQL database dynamically in Linux

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will connect to the MyDb database and then create the "Employee" table dynamically using the "Create table" command.

Program/Source Code:

The source code to create a specified table in MySQL database dynamically in Linux is given below. The given program is compiled and executed successfully on Ubuntu 20.04.

//C program to create a specified table in MySQL database dynamically 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);

    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, "CREATE TABLE Employee(Eid INT PRIMARY KEY AUTO_INCREMENT, Ename VARCHAR(16), Salary INT)")) {
        printf("Unable to create database table in MyDb database\n");
        mysql_close(conn);
        return 1;
    }

    mysql_close(conn);

    printf("Employee table created successfully\n");

    return 0;
}

Output:

$ gcc create_table.c -o create_table  `mysql_config --cflags --libs`
$ sudo ./create_table 
Employee table created successfully

In the above program, we included the mysql.h header file to use MySql connectivity related functions. Here, we created variables serverusernamepassword, 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 create an "employee" table using the mysql_query() function with specified SQL command and then print the "Employee table created successfully" message on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now