How to connect to mysql database from dot net core 6

Published on December 30, 2021
Last updated December 30, 2021

I will be using Visual Studio 2022 ide and a windows form app for this tutorial but the procedure is basically same for any other type of app.

Create a new windows form app and name it as you like. I will be naming it as MySqlConnection.

Add NuGet as a Package Source

In the solution explorer right click on the MySqlConnection project and click on Manage NuGet Packages

Click on the settings icon in the window that appears

In the Package Sources window click on the + icon to add a new package Source

Enter name as Nuget and the Source as

Click Update to save the changes.

Add the mysql nuget package

Now in the NuGet Package Manager Console click on Browse and enter the name of the package as MySql.Data

Click on the package and click Install

Click on the OK button in the preview changes window

and click the I Accept button to accept the license

MySql.Data is a package that contains the mysql driver for .net core and it is now installed.

Open a connection to MySql database

In the Form design add a button and double click on it to open the button click event method.

And also add a list box to display the data read from the mysql database.

Form1.cs Comple Code

using MySql.Data.MySqlClient;
namespace MySqlTest
    public partial class Form1 : Form
        public Form1()

        private void button1_Click(object sender, EventArgs e)
            MySqlConnection con = new MySqlConnection("server=localhost;user=root;database=world;port=3306;password=nikhil");
            MySqlCommand cmd = new MySqlCommand("SELECT Name FROM country;", con);
            MySqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())

Code Explanation

First we are clearing the list box.

Then we are creating a new connection object using the parameters and opening the connection.

Connection parameters are server, user, database, port and password.

Change the parameters to your own database details.

Then we are creating a new command object and passing the connection object to it.

Then we are creating a new data reader object and passing the command object to it.

Then we are reading the data from the data reader and displaying it in the list box.

Finally we are closing the connection and disposing the command and data reader objects.

In this way we can easily connect and perform operations on the mysql database with dot net core 6.

Tags :