简体   繁体   English

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

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

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-我尝试将服务器设置为本地主机,将用户设置为 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.我可以通过mysql工作台连接到mysql服务器,查询数据库。 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.编辑:我注意到错误在我使用 sharpdevelop 时出现,而不是在我使用 Visual Studio 时出现。

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;端口=1234; Database=myDataBase;数据库=我的数据库; Uid=myUsername; uid=我的用户名; Pwd=myPassword;密码=我的密码;

I am running mysql on a computer on a local network.我在本地网络上的计算机上运行 mysql。 MySQL Workbench could connect to that server, but not my c# code. MySQL Workbench 可以连接到该服务器,但不能连接到我的 c# 代码。 I solved my issue by disconnecting from a vpn client that was running.我通过与正在运行的 vpn 客户端断开连接来解决我的问题。

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.总结:如果您打开和关闭连接,Windows 会出于某些愚蠢的原因保留 TCP 端口以供将来使用。 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:这是我在 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:在 Vista/2008 上,您可以使用 netsh 将其更改为:

 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.大多数框架会自动执行此操作,但在我的情况下,应用程序出于某种原因手动处理连接。

Update your connection string as shown below (without port variable as well):更新您的连接字符串,如下所示(也没有port变量):

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

Hope this helps...希望这有助于...

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

In my case the hosting had a whitelist for remote connection to MySql.在我的情况下,托管有一个用于远程连接到 MySql 的白名单。 Try to add your IP to whitelist in hosting admin panel.尝试将您的 IP 添加到托管管理面板中的白名单。

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:以前我有我的连接字符串,因为这个通知端口:3306需要像127.0.0.1:3306那样连接到服务器,或者像那样从服务器中删除Server=127.0.0.1;Port=3306取决于您的 .NET 环境:

"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.它运行良好,直到发生了一些我不确定到底是什么的事情,可能是我的 .NET 应用程序包的最新更新。 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

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.更好的是,确保所有必需的依赖项都存在于将运行代码的机器中。

for users running VS2013对于运行 VS2013 的用户

In windows 10.在 Windows 10 中。

Check if apache service is running.检查 apache 服务是否正在运行。 since it gets replaced with World wide web service.因为它被万维网服务所取代。

run netstat -n to check this.运行 netstat -n 来检查这一点。

stop the service.停止服务。 start apache.启动阿帕奇。 restart the service.重启服务。

I was having the exact same error.我遇到了完全相同的错误。

Here's what you need to do:您需要执行以下操作:

If you are using MAMP, close your server.如果您使用的是 MAMP,请关闭您的服务器。 Then click on the preferences button when you open up MAMP again (before restarting your server of course).然后在您再次打开 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”按钮。

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

If you are accessing the live database by using localhost URL then it will not work.如果您使用 localhost URL 访问实时数据库,则它将不起作用。 Please deploy your service or website on IIS and create URL and then access the database by using new URL, It will work.请在 IIS 上部署您的服务或网站并创建 URL,然后使用新 URL 访问数据库,它将起作用。

In my case by removing portion "port=3306;"在我的情况下,通过删除部分“port = 3306;” from the connection string solved the problem.从连接字符串解决了这个问题。

try this:尝试这个:

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

In case this helps someone, although this is possibly a very specific use case... Today we had this issue in our docker swarm environment.如果这对某人有帮助,尽管这可能是一个非常具体的用例……今天我们在 docker swarm 环境中遇到了这个问题。 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.连接字符串在环境变量中看起来没问题,我们能够从 Workbench 等连接。结果是我们以某种方式将 docker 镜像从 dev 环境推送到了 swarm 环境,并且 dev 镜像有代码更改,这可能会破坏连接字符串。 All we had to do was rerun the pipeline to get the correct image pushed into the swarm environment.我们所要做的就是重新运行管道以将正确的图像推送到 swarm 环境中。

If connection string is ok and you use MAMP on MacOS , make sure to check Allow.network access to MySQL option under MySQL tab.如果连接字符串正常并且您在MacOS上使用MAMP ,请确保选中 MySQL 选项卡下的Allow.network access to MySQL选项。

use SqlConnectionStringBuilder to 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; }
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 上运行,因此如果端口号不同,则不需要提及端口,然后我们需要提及端口

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法连接到任何指定的mysql主机。 C# - unable to connect to any of the specified mysql hosts. c# mySQL异常:无法连接到任何指定的MySQL主机。 通过C# - mySQL Exception: Unable to connect to any of the specified MySQL hosts. through C# :&#39;无法连接到任何指定的MySQL主机。 错误 - :'Unable to connect to any of the specified MySQL hosts.' error 无法连接到任何指定的MySQL主机。 - Unable to connect to any of the specified MySQL hosts. <add name=“MySqlSiteMapProvider” 错误“无法连接到任何指定的MySQL主机。” - ERROR “Unable to connect to any of the specified MySQL hosts.” 获取错误:“无法连接到任何指定的MySQL主机。”在不使用MySQL的应用程序中 - Getting error: “Unable to connect to any of the specified MySQL hosts.” In an application that doesn't use MySQL 仅在发布后出现错误:“无法连接到任何指定的MySQL主机。” - Error only occurs after publishing: “Unable to connect to any of the specified MySQL hosts.” 处理映射的网络驱动器将引发“无法连接到任何指定的MySQL主机。”异常 - Working off mapped network drive throws “Unable to connect to any of the specified MySQL hosts.” exception “无法连接到任何指定的MySQL主机。”在智能设备项目VS2008中 - “Unable to connect to any of the specified MySQL hosts.” in Smart Device Projects VS2008 无法以C#Windows形式连接到任何指定的MySQL主机 - Unable to connect to any of the specified MySQL hosts in c# windows form
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM