How to Connect MYSQL Database to C#?

Devstringx Technologies
3 min readJul 12, 2022

In this blog going to explain about how to connect MYSQL database to C#.

First ensure you have downloaded and introduced the MySQL Connector/NET from the MySQL official site. In this blog, I will utilize the Connector/NET form 6.1.

To interface MySQL information base to a C# application, MySQL gives a progression of classes in the MySQL Connector/Net. All the correspondence between a C# application and the MySQL server is directed through a MySqlConnection Object. Along these lines, before your application can speak with the server, it should launch, arrange, and open a MySqlConnection object.

MySQL is a main open source data set administration framework. It is a multi client, multithreaded information base administration framework.Download MySQL Connector/Net

Download MySQL Connector/Net

It can be downloaded from Mysql developer website https://dev.mysql.com/downloads/ free of cost.

Add Reference

Before we start to connect our application to MySql Database, We need to add the mysql Reference in our project. To do this, right click on project name, and choose Add Reference, then choose “MySql.Data” from the list.

After that under the reference right click on System.Data.SqlXml

And then select copy local value as “true”

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace Test_Automation

{

internal class DatabaseConnectionwithCsharp

{

// Main Method

static public void Main(String[] args)

{

string server = "localhost";

string database = "testdb";

string username = "root";

string password = "password";

string connectionstring = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + username + ";" + "PASSWORD=" + password + ";";

MySqlConnection connection = new MySqlConnection(connectionstring);

connection.Open();

}

}

}

Explanation of variables declared in program:

  • Server: It indicates where our server is hosted, in our case, it’s localhost.
  • Database: It is the name of the database we will use, in our case it’s the database we already created earlier which is testdb.
  • Username: It is our MySQL username.
  • Password: It is our MySQL password.
  • Connectionstring: It contains the connection string to connect to the database, and will be assigned to the connection variable.
  • Connection.Open(); : It opens the Connection.

Conclusion:

In this Blog I demonstrated about the Making connection between MYSQL database to C#.

Originally published at www.devstringx.com on July 11, 2022

--

--

Devstringx Technologies

Devstringx Technologies is highly recommended IT company for custom software development, mobile app development and automation testing services