在 docker 中与网络 SQL 服务器的连接超时,但 ping 有效 [重复]

问题描述 投票:0回答:1

我正在尝试从基于 python:3.10-slim 映像的 docker 容器内连接到网络 SQL 服务器。我可以成功 ping 服务器,但无法通过 pyodbc 和直接从终端连接到服务器。

$ /opt/mssql-tools/bin/sqlcmd -H 10.0.x.xx,xxxx -d DataBaseName -U user
Password: 
Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : Login timeout expired.
Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : TCP Provider: Error code 0x2749.
Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : 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..
$ ping 10.0.x.xx
PING 10.0.x.xx (10.0.x.xx) 56(84) bytes of data.
64 bytes from 10.0.x.xx: icmp_seq=1 ttl=36 time=5.42 ms
64 bytes from 10.0.x.xx: icmp_seq=2 ttl=36 time=5.45 ms
64 bytes from 10.0.x.xx: icmp_seq=3 ttl=36 time=6.07 ms
64 bytes from 10.0.x.xx: icmp_seq=4 ttl=36 time=5.07 ms
64 bytes from 10.0.x.xx: icmp_seq=5 ttl=36 time=7.23 ms
64 bytes from 10.0.x.xx: icmp_seq=6 ttl=36 time=9.06 ms
64 bytes from 10.0.x.xx: icmp_seq=7 ttl=36 time=6.80 ms
64 bytes from 10.0.x.xx: icmp_seq=8 ttl=36 time=4.44 ms
--- 10.0.x.xx ping statistics ---
8 packets transmitted, 8 received, 0% packet loss, time 7011ms
rtt min/avg/max/mdev = 4.441/6.192/9.064/1.377 ms

我测试了一个使用 pyodbc 的最小 python 脚本。它在 Docker 容器外部工作,但当我从 Docker 内部运行它时会出现登录超时:

pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')

import pyodbc

sales_conn = pyodbc.connect(driver="{ODBC Driver 17 for SQL Server}", server="ServerName",
database="DataBaseName", user="user", password="password", encoding="latin1")
print("Connected")
cursor = sales_conn.cursor()

print("Success")

cursor.close()
sales_conn.close()

我已经尝试了网上类似问题的几种解决方案,但我似乎无法让它发挥作用。

python sql-server docker odbc
1个回答
0
投票

我不确定是否是这种情况,但文档和源在此处输入链接描述代码表明 connect 接受连接参数作为单个字符串,因此您应该尝试以下操作:

sales_conn = pyodbc.connect('driver="{ODBC Driver 17 for SQL Server}", server="ServerName"')

此外,如果这是本地数据库,请尝试使用

"localhost:<port>"
作为服务器。

© www.soinside.com 2019 - 2024. All rights reserved.