尝试从 Azure VM 连接到 Azure 托管实例中的 sql 时超时

Timing out while trying to connect to sql in Azure Managed Instance from Azure VM

我正在尝试从 Azure VM 机器中的 python 脚本访问 Azure 托管实例(IP:xxxx.database.windows.net)中 SQL 数据库中的表,但我得到了操作错误如下。我尝试了以下两种不同的方法。

错误:

OperationalError: ('08001', '[08001] [Microsoft][SQL Server Native Client 11.0]TCP Provider: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.\r\n (10060) (SQLDriverConnect); [08001] [Microsoft][SQL Server Native Client 11.0]Login timeout expired (0); [08001] [Microsoft][SQL Server Native Client 11.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (10060)')

connectionString 的第一种方式:

import pandas as pd
from sqlalchemy import create_engine

engine = create_engine("mssql+pyodbc://<username>:<password>@<server>/<database>?driver=SQL+Server+Native+Client+11.0")
query = "select * from table"
df=pd.read_sql(query,engine)

connectionString 的第二种方式:

import pyodbc

server = 'xxx.database.windows.net'
database = 'database'
username = 'username'
password = 'password'   
driver= '{SQL Server Native Client 11.0}'
with pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) as conn:
    with conn.cursor() as cursor:
        cursor.execute("SELECT TOP 3 name, collation_name FROM sys.databases")
        row = cursor.fetchone()
        while row:
            print (str(row[0]) + " " + str(row[1]))
            row = cursor.fetchone()

另外我也试过把驱动改成下面的驱动,还是不行。

{ODBC Driver 11 for SQL Server}
{ODBC Driver 13 for SQL Server}
{ODBC Driver 17 for SQL Server}
{SQL Server Native Client 11.0}

有趣的是,如果我尝试使用非 Azure VM 的本地机器(例如:我的本地机器或其他服务器,我可以RDP 到),我可以访问数据库。但是当我在 Azure VM 机器上尝试时,它超时了。您有解决此问题的想法吗?

感谢您的意见。

所以最后我们发现是防火墙导致了这个问题。我们需要先检查防火墙规则。