How to Connect With MySQL Database in Visual Studio 2022

In this post we will learn how to connect with MySQL database in Visual Studio 2022.

To connect with MySQL we have to install MySql.Data package from NuGet Packages.

First Go to Tools Menu and select NuGet Package Manager > Manage NuGet Packages for Solutions..

Then Go to Browse tab and in the search box type mysql and install MySql.Data package.

MySql.Data

Then Create a new window form and create button with name Connect with Database.

To Create New form Select your project name the right click on that select Add > New Item.

Give name it to form and click on Add button.

Then drag Button control from toolbox and go to properties then rename text to “Connect to Database”. Double click on that button to code for button’s onClick event.

Add this library at the top of your page.

using MySql.Data.MySqlClient;

Open your xampp or any other application which is support MySQL. Then Add these line of code into your button Click event.

Fill your database name, username, password and server name if you not using localhost.

private void button1_Click(object sender, EventArgs e)
        {
             string server = "localhost";
             string database = "your_database_name";
             string username = "your_user_name";
             string password = "Your_password";
             string port = "3306";
            try {
                MySqlConnection conn = new MySqlConnection($"server={server};database={database};username={username};password={password};port={port}");
                conn.Open();
                if (conn.State == ConnectionState.Open)
                {
                    MessageBox.Show("Connected Successfully.");
                }
                if (conn.State == ConnectionState.Closed)
                {

                    conn.Close();
                    MessageBox.Show("Database not connected.");
                }
            
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }

Then click on Start button and run project.

After run your project click on button and test your database connection.

That is it for today, hope it helps. If you have a better approach to resolve this problem please make a comment in comment section below.

If you like this article, you can buy me a coffee. Thanks!

How to Connect With MySQL Database in Visual Studio 2022

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top