I have a MS SQL database in the same network but in other computer. Using the SQL Server Management Studio (SSMS) Express, I can find the database and connect without proble
I have this problem.I can connect with Management Studio (SSMS) but not work with pyodbc. I add version odbc of sql and worked.
change your code to:
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server + ';DATABASE=' + db +';UID=' + user + ';PWD=' + password)
If not work change version 17 to 13 if not to 11 . List versions of ODBC.
Try specifying the port:
import pyodbc
server = r"xxxER\xxxSQLSERV"
db = "xxxDB"
user = "xxx"
password = "xxxx"
port = "1433"
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=' + server + ';PORT=' + port + ';DATABASE=' + db +';UID=' + user + ';PWD=' + password)
If you're still having issues, try using the IP or FQDN of the server.
Try changing the Driver from 'SQL Server' to 'SQL Server Native Client 11.0'.
I had the same error message and this fixed it for me.
"But why ...?"
For those interested in why SQL Server Management Studio (SSMS) can connect to servername\instance
while other applications (like our pyodbc apps) cannot, it's because SSMS keeps an MRU (Most Recently Used) list of port numbers in the Windows registry at
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\SuperSocketNetLib\LastConnect
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSSQLServer\Client\SuperSocketNetLib\LastConnect
Each MRU entry (registry value) looks something like this:
Name: PANORAMA\SQLEXPRESS
Type: REG_SZ
Data: -1006030326:tcp:PANORAMA,52865
Once SSMS has successfully connected by instance name via the SQL Browser service on the remote machine, it can continue to connect by instance name even if the SQL Browser is no longer running on the remote machine, provided that the port number has not changed. Apps that don't use this MRU list (like our pyodbc app) need to have the SQL Browser service running on the remote machine every time they want to connect by instance name.
The most common scenario:
YOUR-PC\SQLEXPRESS
. I try doing that from SSMS on MY-PC
, but it doesn't work because the SQL Browser was installed with "Start Mode" set to "Manual" on YOUR-PC
.YOUR-PC
, and you kindly comply, but you just start the service and forget to change the "Start Mode" setting to "Automatic".YOUR-PC\SQLEXPRESS
port in the MRU). My python app can connect, too.YOUR-PC
restarts, I can connect via SSMS (via the MRU) but my python app cannot (because the SQL Browser service is no longer running on YOUR-PC
).