You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Mysql.Data.MySqlClient在C#/ASP.NET中无法连接MySQL数据库

C#连接MySQL提示“无法连接到指定的MySQL主机”问题排查

我的代码

using MySql.Data.MySqlClient;

namespace DigitalWilds.Models
{
    public class DatabaseConn
    {
        public string status = "failed";
        MySqlConnection conn;
        public string connectionString;
        public DatabaseConn()
        {               
            string webHost = "(host IP)";            
            string dataBase = "DB";            
            string userID = "UID";
            string password = "PASS";
            string port = "3306";

            connectionString = "Server="+webHost+";Port="+port+";Database=" + dataBase+ ";Uid ="+userID+";Pwd="+password;

            try
            {
                conn = new MySqlConnection();
                conn.ConnectionString = connectionString;
                conn.Open();
                status = "success";
                conn.Close(); conn.Dispose();

            }
            catch (MySqlException ex)
            {
                status = ex.Message;
            }
            
        }

    }
}

问题情况

运行代码后始终触发异常,错误信息:

"Unable to connect to any of the specified MySQL hosts."

我已经核对过官方文档和连接字符串格式,确认生成的connectionString符合要求,尝试过添加/移除端口、改用IP:Port格式,都无效。

补充:获取到完整异常信息:

MySql.Data.MySqlClient.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts. ---> MySql.Data.MySqlClient.MySqlException (0x80004005): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.TimeoutException: The operation has timed out. at MySql.Data.Common.StreamCreator.GetTcpStreamAsync(MySqlConnectionStringBuilder settings, CancellationToken cancellationToken, Boolean execAsync) at MySql.Data.Common.StreamCreator.GetStreamAsync(MySqlConnectionStringBuilder settings, CancellationToken cancellationToken, Boolean execAsync) at MySql.Data.MySqlClient.NativeDriver.OpenAsync(Boolean execAsync, CancellationToken cancellationToken) at MySql.Data.MySqlClient.NativeDriver.OpenAsync(Boolean execAsync, CancellationToken cancellationToken) at MySql.Data.MySqlClient.Driver.OpenAsync(Boolean execAsync, CancellationToken cancellationToken) at MySql.Data.MySqlClient.Driver.CreateAsync(MySqlConnectionStringBuilder settings, Boolean execAsync, CancellationToken cancellationToken) at MySql.Data.MySqlClient.Driver.CreateAsync(MySqlConnectionStringBuilder settings, Boolean execAsync, CancellationToken cancellationToken) at MySql.Data.MySqlClient.MySqlPool.CreateNewPooledConnectionAsync(Boolean execAsync, CancellationToken cancellationToken) at MySql.Data.MySqlClient.MySqlPool.GetPooledConnectionAsync(Boolean execAsync, CancellationToken cancellationToken) at MySql.Data.MySqlClient.MySqlPool.TryToGetDriverAsync(Boolean execAsync, CancellationToken cancellationToken) at MySql.Data.MySqlClient.MySqlPool.GetConnectionAsync(Boolean execAsync, CancellationToken cancellationToken) at MySql.Data.MySqlClient.MySqlConnection.OpenAsync(Boolean execAsync, CancellationToken cancellationToken) at MySql.Data.MySqlClient.MySqlConnection.Open() at DigitalWilds.Models.DatabaseConn..ctor() in C:\Users\Me\source\repos\DigitalWilds\Models\DatabaseConn.cs:line 29

请问问题出在哪里?


排查与解决建议

这个错误的核心是TCP网络层面无法和MySQL服务器建立连接,不是连接字符串格式问题(你已经验证格式正确,且超时说明客户端根本没收到服务器响应),按以下步骤排查:

  1. 先验证网络连通性

    • 在运行代码的机器上,执行ping (host IP),如果不通,说明网络链路有问题(比如客户端/服务器防火墙拦截、服务器停机、路由故障)
    • 更关键的是测试3306端口:用PowerShell执行Test-NetConnection (host IP) -Port 3306,或者用telnet (host IP) 3306,如果显示无法连接,说明端口被拦截或MySQL没监听该端口
  2. 检查MySQL服务器配置

    • 确认MySQL服务正在运行:服务器上查看服务状态(Linux用systemctl status mysql,Windows在服务管理器中查看)
    • 检查MySQL绑定地址:打开my.cnf(Linux)或my.ini(Windows),确认bind-address不是127.0.0.1(仅允许本地连接),远程连接需要设为0.0.0.0(允许所有IP)或服务器的实际IP,修改后重启MySQL服务
    • 验证用户连接权限:在MySQL服务器上执行SELECT host, user FROM mysql.user WHERE user='你的用户名';,如果host列是localhost或特定IP,需要改成%(允许所有IP)或你的客户端IP,执行FLUSH PRIVILEGES;生效
  3. 代码优化(避免后续问题)

    • 不要在构造函数中执行数据库连接操作,建议封装成单独的方法
    • 使用using语句自动释放连接资源,无需手动调用Close()和Dispose():
      using (var conn = new MySqlConnection(connectionString))
      {
          conn.Open();
          status = "success";
      }
      
    • 用MySqlConnectionStringBuilder构建连接字符串,避免拼接时的空格或格式错误:
      var builder = new MySqlConnectionStringBuilder
      {
          Server = webHost,
          Port = uint.Parse(port),
          Database = dataBase,
          UserID = userID,
          Password = password
      };
      connectionString = builder.ConnectionString;
      

内容的提问来源于stack exchange,提问作者Tyler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 20:35:12