[英]How can I connect C# with MySQL from Virtual Machine?
I setup a Linux virtual machine on Azure and deployed an Apache web server and MySQL. I setup a Linux virtual machine on Azure and deployed an Apache web server and MySQL. I have a C# application which I want to connect with the MySQL database from my virtual machine.
我有一个 C# 应用程序,我想从我的虚拟机连接到 MySQL 数据库。 I installed the MySQL connector and followed tutorials like this:
我安装了 MySQL 连接器并遵循如下教程:
string connString = "Database=Virtual Machine IP;port=3306;username=root;password=;database=testing";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from Company";
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["CompanyID"].ToString());
}
Console.ReadLine();
But it's not working as I receive this error: "Unable to connect to any of the specified MySQL hosts.", so the connection was not successfully, does anyone know how to do it?但它不起作用,因为我收到此错误:“无法连接到任何指定的 MySQL 主机。”,所以连接不成功,有人知道该怎么做吗?
PS I tried the code with my database from the localhost and it worked. PS我从本地主机上用我的数据库尝试了代码并且它有效。
For the error, you probably need to enable the MySQL port 3306 in the inbound port rule of NSG.对于该错误,您可能需要在 NSG 的入站端口规则中启用 MySQL 端口 3306。 See this document: How to open ports to a virtual machine with the Azure portal .
请参阅此文档: 如何使用 Azure 门户打开虚拟机端口。
For example, add the port 3306 in the destination port ranges and add your client public IP address to the Source IP addresses in the virtual network---networking---inbound port rules.例如,在目标端口范围中添加端口 3306,并将您的客户端公共 IP 地址添加到虚拟网络---网络---入站端口规则中的源 IP 地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.