user8662191
user8662191

Reputation:

Can't connect to mySQL in C#

I'm trying to connect mySQL database in my c# application but I'm stuck with a very short code that doesn't work.

I've tried a bunch of different code but all of them failed. I also tried to use a remote phpmyadmin database and a localhost database, none of them worked.

I'm connected to both of them and copy-pasted their logins in my code. I've disabled firewalls on my phpmyadmin server. I've open my 3306 port on my PC.

using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace Tests
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            string connetionString;
            SqlConnection cnn;
            connetionString = @"Data Source=localhost;Initial Catalog=my_projects;User ID=root;Password=123456";
            cnn = new SqlConnection(connetionString);
            cnn.Open();
            MessageBox.Show("Connection Open  !");
            cnn.Close();
        }
    }
}

It should pop a message box with "Connection Open !" but it actualy loads for 30 seconds and gives me an error message: "The server can not be found or is not accessible".

Do you have any idea? My code is very short and all the searches I did where similar to the code I got there.

Upvotes: 0

Views: 2861

Answers (1)

Steve
Steve

Reputation: 216243

First you need to download the MySql data connector for .NET. You can find it here at https://dev.mysql.com/downloads/connector/net/. Next, after installing it, you need to add a reference to the MySql library to your project. See here how to do it

Or you can simply use the NuGet Package Manager to download and install the connector automatically.

In any case, after the correct installation and referencing the library, you should add, to your cs file, the using MySql.Data.MySqlClient; line and now you are ready to use the classes required to connect to MySql and work with its data.

So your code should be

using MySql.Data.MySqlClient;

... other code ....

private void Button1_Click(object sender, EventArgs e)
{

    try
    {
        string connetionString = @"Server=localhost;Database=my_projects;User ID=root;Password=123456";
        using(MySqlConnection cnn = new MySqlConnection(connetionString))
        {
            cnn.Open();
            MessageBox.Show("Connection Open  !");
        }
    }
    catch(Exception ex)
    {
        MessageBox.Show("Cannot open connection: Reason:" + ex.Message);
    }

}

Remember that the connection to your database contains unmanaged resources and you should always add the using statement around these kind of objects.

Upvotes: 2

Related Questions