• June 13, 2021

PHSARIT

Bring Technology Ideas with you

 Simple Connection to MySql Server using C#.net

Using C#.net to connect to database using MySQL server, C# or dot net framework would need a class or library of connection driver (mysql connector). By installing this connector, your dotnet application will be able to connect to MySQL server with your references. Go to your project solution, right click Add References

    Select on Extensions then tick on Mysql.Data after that click Ok

      In your Window Form using C#, please code as below:

        Source codes:

        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.Data;
        using System.Drawing;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        using System.Windows.Forms;
        using MySql.Data.MySqlClient;
        
        namespace SQL_Insert
        {
            public partial class Form1 : Form
            {
               MySqlConnection cn;
                public Form1()
                {
                    InitializeComponent();
                }
        
                private void Form1_Load(object sender, EventArgs e)
                {
                    //declare connection to mysql server
                    String StringConnection;
                    StringConnection = "server=localhost; userid=root; password=; database=pos;";
                    cn = new MySqlConnection(StringConnection);
                    try
                    {
                        cn.Open(); //open connection
                        MessageBox.Show("Connected successfully");
                    }
                    catch (Exception ex)
                    {
                        //if there is no connection, it will show
                        MessageBox.Show(ex.ToString());
                    }
                }
            }
        }
        

        Software requirements (WAMP Server, Visual Studio, and MySQL Connector)

        Related post