c# Mysql连接仅在本地主机上工作

本文关键字:主机 工作 Mysql 连接 | 更新日期: 2023-09-27 18:13:15

我在c#中连接到mysql数据库,只要我输入服务器地址为"localhost"或其ip,它就能正常工作,但如果我尝试远程ip,它会失败:

Error: 0 : Unable to connect to any of the specified MySQL hosts.

代码如下:

server = Properties.Settings.Default.DBHost;
port = Properties.Settings.Default.DBPort;
database = Properties.Settings.Default.DBName ;
uid = Properties.Settings.Default.DBUser;
password = Properties.Settings.Default.DBPassword ;
string connectionString;
connectionString = "SERVER=" + server + ";" + "PORT=" + port + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
[...]
if (this.OpenConnection() == true){
    // exec db operations
}
else{
    MessageBox.Show("Database Connection Error.");
}

测试:

  • 没有防火墙限制
  • 不同电脑出现相同错误
  • 已经尝试使用不同的远程数据库,所有数据库都具有设置的权限,并且可以从其他来源访问

c# Mysql连接仅在本地主机上工作

如果是你的mysql服务器,那么

  • 检查端口是否打开。(可能是3306年)
  • 修改my.ini文件中的绑定地址(从127.0.0.1改为0.0.0.0)
  • 再次检查您尝试连接到服务器的用户是否具有必要的权限

如果不是你的mysql服务器,那么

  • 询问提供者是否支持远程连接

首先你必须检查你的服务器是否支持远程MySQL database Connection,然后

你可以试试这个MySQL Connection String Builder的例子,我一直在工作…无错误:

_connectionStr = new MySqlConnectionStringBuilder
            {
                Server = "127.0.0.1",
                Database = myDatabase,
                UserID = myUserName,
                Password = myPassword,
                ConnectionTimeout=60,
                Port = 3306,
                AllowZeroDateTime = true
            };
            _con = new MySqlConnection(_connectionStr.ConnectionString);
            try
            {
                _con.Open();
            }
            catch
            {
                MessageBox.Show("Error, help i can't get connected!");
            }

希望这有效!

也许你的MySQL服务器没有配置为监听任何你的IP接口。也许它只是在监听你的"localhost:3306"

检查你的MySQL服务器配置文件"bind-address"

相关文章: