الأخبار

How to connect to MySQL Database to C# Language

Connect C# to MySQL

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.


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()
        {
            InitializeComponent();
        }
        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);
            try
            {
                cnn.Open();
                MessageBox.Show ("Connection Open ! ");
                cnn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Can not open connection ! ");
            }
        }
    }
}

Multiple servers

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

myConnectionString="Server=myServerAddress;Port=1234;Database=testDB;
Uid=root;Pwd=abc123;
The defaqult MySql port is 3306 and if you use Unix socket the value will ignored.

Note:

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