我尝试使用以下示例代码连接到在 Azure VM 上运行的 SQL 服务器(已定义 SQL 用户名和密码):
$SqlCredential = Get-AutomationPSCredential -Name $SqlCredentialAsset
# Get the username and password from the SQL Credential
$SqlUsername = $SqlCredential.UserName
$SqlPass = $SqlCredential.GetNetworkCredential().Password
# Define the connection to the SQL Database
$Conn = New-Object System.Data.SqlClient.SqlConnection("Server=tcp:$SqlServer,$SqlServerPort;Database=$Database;User ID=$SqlUsername;Password=$SqlPass;Trusted_Connection=False;Encrypt=True;")
此代码在我连接到 Azure SQL 数据库时有效,但在连接到在 Azure VM 上运行的 SQL 时无效。
抛出的错误是:
Error occured: Exception calling "Open" with "0" argument(s):
"A network-related or instance-specific error occurred while establishing a
connection to SQL Server. The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
(provider: TCP Provider, error: 0 - No such host is known.)"
我已在虚拟机上验证 SQL 远程连接已启用,并且包括定义的 TCP 端口 1433。
最佳答案
可能是网络相关问题。如果您已在虚拟机上验证 SQL 远程连接已启用,并且已定义 TCP 端口 1433。此外,在附加到虚拟机的 NSG 的入站端口规则和虚拟机内部的 Windows 防火墙中打开了端口 1433。您可以使用 telnet在本地验证此端口。
此外,您可以指定 $SqlServer= "sqlvmlabel.eastus.cloudapp.azure.com"
,这是 Azure VM 的公共(public) DNS 名称。以下是使用 SQL 身份验证的连接字符串示例。
Server=sqlvmlabel.eastus.cloudapp.azure.com;Integrated Security=false;User ID=<login_name>;Password=<your_password>
关于用于连接到 Azure VM 上运行的 SQL 服务器的 Azure Runbook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54230739/