Home »
.Net »
C# Programs
C# program to insert a record to MySQL table
Here, we will learn how to insert a record to MySQL table using C# program?
By Nidhi Last updated : April 04, 2023
Problem Statement
In this program, here we will connect to the MySQL database and then insert a record into the "employee" table.
C# code to insert a record to MySQL table
The source code to insert a record in the MySql database is given below. The given program is compiled and executed successfully.
// C# program to insert a record in MySql database.
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("INSERT INTO employee(eid,ename, salary) VALUES(@eid,@ename,@salary)", conn);
cmd.Parameters.AddWithValue("@eid", 101);
cmd.Parameters.AddWithValue("@ename", "Amit Kumar");
cmd.Parameters.AddWithValue("@salary", 43200);
cmd.Prepare();
cmd.ExecuteNonQuery();
Console.WriteLine("Record inserted successfully");
conn.Close();
}
}
Output
Record inserted 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 insert a record into the "employee" table using ExecuteNonQuery() method of MySqlCommand class and then print the "Record inserted successfully" message on the console screen.
C# Database Programs »