How to connect to MySQL Database to C# ?


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.


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 ! ");
            }
        }
    }

}

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;"



Post a Comment

0 Comments