How to connect mysql database using C#

This article shows you how to connect mysql database to asp.net mvc web application using MySql Connector/.Net.In order to connect with mysql database using C# application Mysql provides a series of predefined classes in mysql connector/.Net to perform various operations on mysql database.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 for dot net from mysql official site with free of cost.Click below link to download. Download mysql connector installor.

Before we start using mysql connector we need to add the mysql connector references to our project.
1.Right click on references --> add reference --> browse for 'MySql.Data' and add.

How to connect mysql database using C#

2.Now add MySql Library namespace in C# project like below.
using MySql.Data.MySqlClient;


Specifying Connection string in Mysql

1.mysql connection string in C# application:
string myConnectionString = "server=localhost;database=testDB;uid=root;pwd=pass123;";
2.For multiple servers:
myConnectionString = Server=server1, server2;database=testDB;uid=root;pwd=abc123;";
Note:The above connection string will needed when connect to a server in a replicated server configuration without concern on which server to use.
3.To specify TCP port in connection string:
myConnectionString="Server=myServerAddress;Port=1234;Database=testDB;Uid=root;Pwd=abc123;

The following program creates a object to MySqlConnection class and opens 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 conString = null;
            MySqlConnection connection;
            conString = "server=localhost;database=testDatabase;uid=root;pwd=passwd123;";
            connection = new MySqlConnection(conString);
            try
            {
                connection.Open();
                MessageBox.Show ("Connection Opened ! ");
                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Can not open connection ! ");
            }
        }
    }
}

How to connect mysql database using C# How to connect mysql database using C# Reviewed by raviteja swayampu on 02:45:00 Rating: 5

No comments: