无法连接到任何指定的 mysql 主机。C# MySQL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17993657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:00:14  来源:igfitidea点击:

Unable to connect to any of the specified mysql hosts. C# MySQL

c#mysqlvisual-studio-2010sharpdevelop

提问by Opax Web

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-

我曾尝试将服务器设置为 localhost,将用户设置为 root,但出现以下错误-

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.

我可以通过mysql workbench连接到mysql服务器,查询数据库。只有代码不起作用。编辑:我注意到错误在我使用sharpdevelop而不是在使用Visual Studio时出现。

回答by Tamim Al Manaseer

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

有时连接字符串中参数的间距和顺序很重要(基于个人经验和漫漫长夜:S)

So stick to the standard format here

所以坚持这里的标准格式

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

服务器=我的服务器地址;端口=1234;数据库=我的数据库;uid=我的用户名;密码=我的密码;

回答by Lamloumi Afif

use SqlConnectionStringBuilderto simplify the connection

用于SqlConnectionStringBuilder简化连接

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; }

回答by Czar Pino

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

刚刚遇到了同样的问题。在目标机器上安装 .NET 框架解决了这个问题。

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

更好的是,确保所有必需的依赖项都存在于将运行代码的机器中。

回答by Shafeek Ajmal

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

确保您的数据库服务器正在运行,如果它没有运行,那么它无法建立连接,并且默认情况下 mysql 在 3306 上运行,因此如果端口号不同,则不需要提及端口,然后我们需要提及端口

回答by BlueRaja - Danny Pflughoeft

Since this is the top result on Google:

由于这是 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.

总结:如果您打开和关闭连接,Windows 会出于某些愚蠢的原因保留 TCP 端口以供将来使用。多次执行此操作后,它会耗尽可用端口。

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

这是我在 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)

您需要创建它们。默认情况下它们不存在。

在 Vista/2008 上,您可以使用 netsh 将其更改为:

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

...but the realsolution 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.

...但真正的解决方案是使用连接池,以便“打开”连接真正重用现有连接。大多数框架会自动执行此操作,但在我的情况下,应用程序出于某种原因手动处理连接。

回答by gondwe

for users running VS2013

对于运行 VS2013 的用户

In windows 10.

在 Windows 10 中。

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

检查 apache 服务是否正在运行。因为它被万维网服务所取代。

run netstat -n to check this.

运行 netstat -n 来检查这一点。

stop the service. start apache. restart the service.

停止服务。启动阿帕奇。重启服务。

回答by Murat Y?ld?z

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

更新您的连接字符串,如下所示(也没有port变量):

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

Hope this helps...

希望这可以帮助...

回答by Jimmy

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.

我在本地网络上的计算机上运行 mysql。MySQL Workbench 可以连接到该服务器,但不能连接到我的 c# 代码。我通过与正在运行的 vpn 客户端断开连接来解决我的问题。

回答by Johnbosco Adam

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

有时问题可能出在您的 Windows 防火墙上,请确保您的服务器允许访问与您的 mysql 数据库关联的所有端口。

回答by justinpees

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).

如果您使用 MAMP,请关闭您的服务器。然后在您再次打开 MAMP 时单击首选项按钮(当然在重新启动服务器之前)。

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

然后您需要单击端口选项卡,然后单击“将 Web 和 MySQL 端口设置为 80 和 3306”按钮。