Home »
.Net »
C# Programs
C# program to create a table in MySQL database dynamically
Here, we will learn how to create a table in MySQL database dynamically using C# program?
By Nidhi Last updated : April 04, 2023
Problem Statement
In this program, here we will connect to MySQL and create a specified table in the database dynamically.
C# code to create a table in MySQL database dynamically
The source code to create a table in the MySql database dynamically is given below. The given program is compiled and executed successfully.
// C# program to create a table in MySql
// database 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;database=Sample_DB";
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand cmd = new MySqlCommand("create table employee (eid int, ename varchar(16), salary int) ", conn);
cmd.ExecuteNonQuery();
Console.WriteLine("Table employee created successfully");
conn.Close();
}
}
Output
Table employee 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 database using MySqlConnection class and then create the "employee" table in the database using ExecuteNonQuery() method of MySqlCommand class and print the "Table employee created successfully" message on the console screen.
C# Database Programs »