Home »
.Net »
C# Programs
C#.Net program to create a database in MySql dynamically
Here, we are going to learn how to create a database in MySql dynamically in C#?
Submitted by Nidhi, on February 10, 2021
In this program, here we will connect to MySQL and create a specified database dynamically.
Program:
The source code to create a database in MySQL dynamically is given below. The given program is compiled and executed successfully.
//C#.Net program to create a database in
//MySql dynamically.
using MySql.Data.MySqlClient;
using System;
class Program
{
static void Main(string[] args)
{
//Connection String to connect with MySQL database.
string connString = "server=localhost;userid=root;password=root";
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand cmd = new MySqlCommand("create database Sample_DB", conn);
cmd.ExecuteNonQuery();
Console.WriteLine("Database Sample_DB created successfully");
conn.Close();
}
}
Output:
Database Sample_DB created successfully
Press any key to continue . . .
Explanation:
In the above program, we imported a namespace MySql.Data.MySqlClient to establish the connection with the MySql database. Then we created a class Program that contains the Main() method.
The Main() method is the entry point for the program. In the Main() method, we created a connection string variable ConnString that contains the database connectivity credentials. After that we established the connection to the MySql using MySqlConnection class and then create the "Sample_DB" database using ExecuteNonQuery() method of MySqlCommand class and print the "Database Sample_DB created successfully" message on the console screen.
C# Database Programs »