C# : To Connect to a MySql Database

Leave a Comment
Things Needed:
You should have installed MySQL and MySQL Connector/NET. You can download installers from http://dev.mysql.com/downloads
Microsoft Visual C# or Visual Studio.
Download and install MySql for Windows.
DownloadHere

To use the methods in the MySQL Connector/NET you should add a reference to it. Right click your project in the Solution Explorer and click Add Reference… In the .NET tab, chose MySql.Data and click ok.

       
  
using System;
using MySql.Data.MySqlClient;

public class Example
    {

    static void Main()
        {
       
        String str = @"server=localhost;database=project;userid=root;password=;";
        MySqlConnection con = null;
        try
            {
            con = new MySqlConnection(str);
            con.Open(); //open the connection
            Console.Write("Sucess");
            }
        catch (MySqlException err) //We will capture and display any MySql errors that will occur
            {
            Console.WriteLine("Error: " + err.ToString());
            }
        finally
            {
            if (con != null)
                {
                con.Close(); //safely close the connection
                }
            }
        Console.ReadLine();
        }
    }

       
 

0 comments:

Post a Comment