Pyodbc 无法解析本地主机,但可以在 IP 地址 127.0.0.1 上工作

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

我在Python3.8中使用Pyodbc连接到本地主机上的SQL Server。

在连接字符串中,我可以使用IP地址(127.0.0.1)连接到数据库,但是在使用localhost时出现错误。如何解决这个问题?

cnxn_str = ("Driver={ODBC Driver 17 for SQL Server};"
            "Server=127.0.0.1;" # this works
            "Database=**;"
            "UID=**;"
            "PWD=**;"
           )

如果我将IP地址替换为localhost,则失败。

cnxn_str = ("Driver={ODBC Driver 17 for SQL Server};"
            "Server=localhost;" # failed
            "Database=**;"
            "UID=**;"
            "PWD=**;"
           )

错误:

      1 cnxn_str = ("Driver={ODBC Driver 17 for SQL Server};"
      2             "Server=localhost;"
      3             "Database=**;"
      4             "UID=**;"
      5             "PWD=**;"
      6            )
----> 7 cnxn = pyodbc.connect(cnxn_str)

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

我可以在本地 ping localhost,并且 localhost 在浏览器中工作。

PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.061 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.051 ms

等/主机:

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1   localhost
255.255.255.255 broadcasthost
::1             localhost
python sql-server python-3.x odbc pyodbc
1个回答
0
投票

MS ODBC 驱动程序将

localhost
解析为您的计算机名称,但您的主机名未解析为
127.0.0.1
::1
,因此出现问题。您可以在
/etc/hosts/
:

中添加带有主机名的别名
127.0.0.1   localhost   YOUR-HOSTNAME

现在,我知道通常您应该能够 ping 通您的主机名,并且它应该解析为与 localhost 相同的 IP,而无需在主机配置中手动处理此问题,但这是一个不同的问题。


相关:

https://github.com/mkleehammer/pyodbc/issues/1125

https://github.com/dotnet/SqlClient/issues/2075

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