Q:

C program to create MySQL database dynamically in Linux

belongs to collection: C MySQL Programs

0

C program to create 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 MySQL server and create the "MyDb" database in MySQL dynamically using the "Create database MyDb" command.

Program/Source Code:

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

//C program to create 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";

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

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

    if (mysql_query(conn, "CREATE DATABASE MyDb")) {
        printf("Unable to create database\n");
        mysql_close(conn);
        return 1;
    }

    mysql_close(conn);

    printf("Database created successfully\n");
    return 0;
}

Output:

$ gcc create_db.c -o create_db  `mysql_config --cflags --libs`
$ sudo ./create_db

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

Here, we connected to the MySQL server and then created the MyDb database in the MySql server using mysql_query() function with specified SQL command and then print "Database 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)

C program to create a table in MySQL database dyna... >>
<< C program to get MySQL version using SELECT statem...