I use Pyodbc in Python3.8 to connect to the SQL Server on localhost.
In the connection string, I can connect to the database using IP address(127.0.0.1), but I got an error when using localhost. How to solve this issue?
cnxn_str = ("Driver={ODBC Driver 17 for SQL Server};"
"Server=127.0.0.1;" # this works
"Database=**;"
"UID=**;"
"PWD=**;"
)
If I replace the IP address with localhost, it's failed.
cnxn_str = ("Driver={ODBC Driver 17 for SQL Server};"
"Server=localhost;" # failed
"Database=**;"
"UID=**;"
"PWD=**;"
)
error:
I can ping localhost on my local, and localhost works in browsers.
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/hosts:
##
# 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
1条答案
按热度按时间nqwrtyyt1#
The MS ODBC driver resolves
localhost
to your machine name, but your hostname doesn't resolve to127.0.0.1
or::1
, hence the issue. You can add an alias with your hostname in/etc/hosts
:Now, I understand that normally you should be able to ping your hostname and it should resolve to the same IP as localhost without having to handle this manually in the hosts config, but that's a different issue.
Related:
https://github.com/mkleehammer/pyodbc/issues/1125
https://github.com/dotnet/SqlClient/issues/2075