26

I am getting the above error when I execute the code -

MySqlConnection mysqlConn=new MySqlConnection("server=127.0.0.1;uid=pankaj;port=3306;pwd=master;database=patholabs;");
        mysqlConn.Open();

I have tried setting server to localhost, user to root but I get the following error-

Error: 0 : Unable to connect to any of the specified MySQL hosts.
System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Unhandled exception</Description><AppDomain>DBSync.exe</AppDomain><Exception><ExceptionType>MySql.Data.MySqlClient.MySqlException, MySql.Data, Version=6.7.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d</ExceptionType><Message>Unable to connect to any of the specified MySQL hosts.</Message><StackTrace>
at  MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.CreateNewPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at DBSync.MainForm.BtnCalculateClick(Object sender, EventArgs e) in c:\Documents  and Settings\Test01\My Documents\SharpDevelop Projects\DBSync\DBSync\MainForm.cs:line 51
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message&amp;amp; m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message&amp;amp; m)
at System.Windows.Forms.ButtonBase.WndProc(Message&amp;amp; m)
at System.Windows.Forms.Button.WndProc(Message&amp;amp; m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp;amp; m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp;amp; m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp;amp; msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at DBSync.Program.Main(String[] args) in c:\Documents and Settings\Test01\My Documents\SharpDevelop Projects\DBSync\DBSync\Program.cs:line 27</StackTrace><ExceptionString>MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.CreateNewPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at DBSync.MainForm.BtnCalculateClick(Object sender, EventArgs e) in c:\Documents and Settings\Test01\My Documents\SharpDevelop Projects\DBSync\DBSync\MainForm.cs:line 51
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message&amp;amp; m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message&amp;amp; m)
at System.Windows.Forms.ButtonBase.WndProc(Message&amp;amp; m)
at System.Windows.Forms.Button.WndProc(Message&amp;amp; m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp;amp; m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp;amp; m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp;amp; msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at DBSync.Program.Main(String[] args) in c:\Documents and Settings\Test01\My Documents\SharpDevelop Projects\DBSync\DBSync\Program.cs:line 27</ExceptionString><DataItems><Data><Key>Server Error Code</Key><Value>1042</Value></Data></DataItems></Exception></TraceRecord>

I can connect to the mysql server through mysql workbench and query the database. It is only the code that doesn't work. Edit: I have noticed that the error crops up when I am using sharpdevelop and not when I am using Visual Studio.

18 Answers 18

40

Sometimes spacing and Order of parameters in connection string matters (based on personal experience and a long night :S)

So stick to the standard format here

Server=myServerAddress; Port=1234; Database=myDataBase; Uid=myUsername; Pwd=myPassword;

2
  • 1
    The documentation states "If you do not specify a server, localhost is assumed." I used to rely upon this default but when it stopped working I had to make it explicit. It continues to be unnecessary to specify the default port 3306.
    – H2ONaCl
    Apr 20, 2018 at 23:50
  • Spot on about a long night!
    – Farax
    Dec 8, 2018 at 7:26
16

I am running mysql on a computer on a local network. MySQL Workbench could connect to that server, but not my c# code. I solved my issue by disconnecting from a vpn client that was running.

6
  • 46
    Funny. I had the same issue again, did a google search, found my own post (without paying attention to who posted). It solved my problem again. Was going to upvote :)
    – Jimmy
    Jun 13, 2017 at 17:28
  • 3
    Upvoted on your behalf. I've done that several times. Thanks past me.
    – Joshua
    Jan 19, 2018 at 16:32
  • 3
    Haha! Thanks current Joshua.
    – Jimmy
    Jan 19, 2018 at 19:58
  • 1
    Read your comment and gave it no chance.. then tried it and it worked, hats off..
    – Pete Kozak
    Nov 11, 2019 at 12:40
  • 1
    I already knew it, but today I forgot and I had to look for the answer. What my daughter would say to me at this moment: you dummy! :)
    – jrivam
    Jun 8, 2020 at 11:58
14

Since this is the top result on Google:

If your connection works initially, but you begin seeing this error after many successful connections, it may be this issue.

In summary: if you open and close a connection, Windows reserves the TCP port for future use for some stupid reason. After doing this many times, it runs out of available ports.

The article gives a registry hack to fix the issue...

Here are my registry settings on XP/2003:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\MaxUserPort 0xFFFF (DWORD)
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\MaxUserPort\TcpTimedWaitDelay 60 (DWORD)

You need to create them. By default they don't exists.

On Vista/2008 you can use netsh to change it to something like:

netsh int ipv4 set dynamicport tcp start=10000 num=50000

...but the real solution is to use connection pooling, so that "opening" a connection really reuses an existing connection. Most frameworks do this automatically, but in my case the application was handling connections manually for some reason.

2
  • That's exactly my problem. Do you know how are you supposed to do connection pooling? (should I implement it manually or use a framework) Mar 29, 2019 at 15:07
  • 1
    UPDATE: It seems that connection pooling is enabled by default: stackoverflow.com/questions/26089420/… Mar 29, 2019 at 15:14
6

Update your connection string as shown below (without port variable as well):

MysqlConn.ConnectionString = 
    "Server=127.0.0.1;Database=patholabs;Uid=pankaj;Pwd=master;"
5

I found the solution to my problem, I was having the same issue. Previously I had my connection string as this notice the port :3306 needs to be either attached to the server like that 127.0.0.1:3306 or removed from server like that Server=127.0.0.1;Port=3306 depending on your .NET environment:

"Server=127.0.0.1:3306;Uid=username;Pwd=password;Database=db;"

It was running fine until something happened which I am not sure exactly what it is, might be a recent update to my .NET application packages. It looks like format and spacing of the connection string is important. Anyways, the following format seems to be working for me:

"Server=127.0.0.1;Port=3306;Uid=username;Pwd=password;Database=db;"

Try either of the versions and see which one works for you.

Also I noticed that you are not using camel casing, this could be it. Make sure your property names are in capital casing like that

Server
Port
Uid
Pwd
Database
2
  • 1
    This worked for me when trying to connect to MySQL using "Pomelo.EntityFrameworkCore.MySQL" on MacOS using dotnet-ef.
    – Dan
    Oct 14, 2022 at 13:44
  • This also worked for me but in my case I also needed to use the matching port that Azure was using for a "MySQL In App" database. It was not the standard 3306. Server=127.0.0.1;Port=53482;Uid=xxxxx;Pwd=xxxxxxx;Database=localdb;
    – james2code
    Feb 12 at 17:34
1

Sometime the problem could be on your windows firewall, make sure your server allow access to all port associated with your mysql database.

1

Try this:

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "127.0.0.1";
conn_string.Port = 3306;
conn_string.UserID = "root";
conn_string.Password = "myPassword";
conn_string.Database = "myDB";



MySqlConnection MyCon = new MySqlConnection(conn_string.ToString());

try
{
    MyCon.Open();
    MessageBox.Show("Open");
    MyCon.Close();
    MessageBox.Show("Close");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
1

In my case the hosting had a whitelist for remote connection to MySql. Try to add your IP to whitelist in hosting admin panel.

0

use SqlConnectionStringBuilder to simplify the connection

System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Initial Catalog"] = "Server";
builder["Data Source"] = "db";
builder["integrated Security"] = true;
string connexionString = builder.ConnectionString;
SqlConnection connexion = new SqlConnection(connexionString);
try { connexion.Open(); return true; }
catch { return false; }
2
  • what is the problem exactly? Aug 2, 2013 at 8:49
  • 1
    Same. Unable to connect to any of the specified mysql hosts.
    – Opax Web
    Aug 2, 2013 at 9:05
0

Just ran into the same problem. Installing the .NET framework on the target machine solved the problem.

Better yet, make sure all required dependencies are present in the machine where the code will be running.

1
  • This answer doesn't make any sense.
    – Elmue
    Apr 29, 2021 at 15:54
0

for users running VS2013

In windows 10.

Check if apache service is running. since it gets replaced with World wide web service.

run netstat -n to check this.

stop the service. start apache. restart the service.

1
  • since the service is persistent as i have noticed, i have to run this on command prompt everytime a do a restart until i find a better solution net stop w3SVC net start apache2.4 (depending on version)
    – gondwe
    Aug 7, 2015 at 12:53
0

I was having the exact same error.

Here's what you need to do:

If you are using MAMP, close your server. Then click on the preferences button when you open up MAMP again (before restarting your server of course).

Then you will need to click on the ports tab, and click the button "Set Web and MySQL Ports to 80 & 3306".

0

If you are accessing the live database by using localhost URL then it will not work. Please deploy your service or website on IIS and create URL and then access the database by using new URL, It will work.

0

In my case by removing portion "port=3306;" from the connection string solved the problem.

0

try this:

    try
            { //run something
}
catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
0

In case this helps someone, although this is possibly a very specific use case... Today we had this issue in our docker swarm environment. The connection string looked ok in environment variables, and we were able to connect from Workbench etc. It turned out that we had somehow pushed the docker image from the dev environment into the swarm environment, and the dev image had code changes which would have broken the connection string. All we had to do was rerun the pipeline to get the correct image pushed into the swarm environment.

0

If connection string is ok and you use MAMP on MacOS, make sure to check Allow network access to MySQL option under MySQL tab.

-1
using System;
using System.Linq;
using MySql.Data.MySqlClient;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            // add here your connection details
            String connectionString = "Server=localhost;Database=database;Uid=username;Pwd=password;";
            try
            {
                MySqlConnection connection = new MySqlConnection(connectionString);
                connection.Open();

                Console.WriteLine("MySQL version: " + connection.ServerVersion);
                connection.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            Console.ReadKey();
        }
    }
}

make sure your database server is running if its not running then its not able to make connection and bydefault mysql running on 3306 so don't need mention port if same in case of port number is different then we need to mention port

Not the answer you're looking for? Browse other questions tagged or ask your own question.