Connect C# to MySQL

How to connect mysql databse to c# application

In order to connect MySQL database to a C# application, MySQL provides a series of classes in the MySQL Connector/Net. All the communication between a C# application and the MySQL server is routed through a MySqlConnection Object. So, before your application can communicate with the server, it must instantiate, configure, and open a MySqlConnection object.

Download MySQL Connector/Net

You can download MySQL Connector/Net from Mysql developer website free of cost. Click the following link.... Download MySQL Connector/Net

Add Reference

Before you start to connect your application to MySql, you need to add add the mysql Reference in your project. To do so, right click our project name, and choose Add Reference, then choose "MySql.Data" from the list.

How to add mysql database reference to c# application

Next, you need to add MySql Library in your C# project.

using MySql.Data.MySqlClient;

C# MySQL connection string

string myConnectionString = "server=localhost;database=testDB;uid=root;pwd=abc123;";

The following C# Program is used to create a MySqlConnection object, assign the connection string, and open the connection.

using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace WindowsApplication1
    public partial class Form1 : Form
        public Form1()
        private void button1_Click(object sender, EventArgs e)
            string connetionString = null;
            MySqlConnection cnn ;
			connetionString = "server=localhost;database=testDB;uid=root;pwd=abc123;";
            cnn = new MySqlConnection(connetionString);
                MessageBox.Show ("Connection Open ! ");
            catch (Exception ex)
                MessageBox.Show("Can not open connection ! ");

Multiple servers

How to connect mysql Multiple database to .Net application

The following connection string will needed when connect to a server in a replicated server configuration without concern on which server to use.

myConnectionString = Server=server1, server2;database=testDB;uid=root;pwd=abc123;";

Specifying TCP port


The defaqult MySql port is 3306 and if you use Unix socket the value will ignored.


MySQL Connector/Net does not support Express versions of Microsoft products, including Microsoft Visual Web Developer.

NEXT.....Byte array to string