我在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=**;"
)
如果我用localhost替换IP地址,它就失败了。
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
etc/主机:
##
# 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
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