如何使用C#中的计算机名称连接到mysql



我想用我的计算机名作为主机连接到mysql。我得到这个错误:

无法连接到任何指定的mysql主机

当我用localhost127.0.0.1更改主机时,一切正常。

我用我的计算机名COMP-18TN直接在mysql工作台中测试连接。MySQL工作台可以连接到该服务器。但不是我的c#代码。

你会发现我的代码如下:

string host = "COMP-18TN";
string DatabaseName = "Cars_DB";
string UserName ="root_name";
string Password ="pass";
string connString = string.Format("Server={0}; database={1}; UID={2}; password={3}",
host, DatabaseName, UserName, Password);
MySqlConnection conn = new MySqlConnection(connString);
try
{
conn.Open();

}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

您可以尝试在C:WindowsSystem32driversetchosts:中的hosts文件中添加一个条目

127.0.0.1 COMP-18TN

这样,您的计算机名称将解析为您知道有效的本地IP。

最新更新