问题
I am using pyodbc to retrieve data from MSSQL and this is the code I am using:
import pyodbc
server = 'xxxxxxxx\DEV'
database = 'SandBox'
username = 'zzzzzzz'
password = 'xxxxxxx'
driver = '{SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';PORT=4853;SERVER='+server+';PORT=4853;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("select * from fieldscreenscheme ")
row = cursor.fetchone()
if row:
print row
This is the error massage I got:
cnxn = pyodbc.connect('DRIVER='+driver+';PORT=43853;SERVER='+server+';PORT=43853;DATABASE='+database+';UID='+username+';PWD='+ password)
pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53); [01S00] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)')
I installed the ODBC driver. Any recommendation how to solve this error?
I looked at these two but did not help me to solve this.
Python - Can't connect to MS SQL
pyodbc + MySQL + Windows: Data source name not found and no default driver specified
Microsoft Documentation: https://github.com/Microsoft/azure-docs/blob/master/articles/sql-database/sql-database-develop-python-simple.md
回答1:
Two problems:
- Normally, one supplies either the
\INSTANCENAME
or the port number, not both. - ODBC connection strings for SQL Server do not use
PORT=
, they put the port number in theSERVER=
parameter, e.g.,SERVER=xxxxxxxx,43853
. (Note that the instance name is omitted and the separator is a comma, not a colon.)
回答2:
I've met same problem and fixed it changing connection string like below. Writing
driver = '{ODBC Driver 13 for SQL Server}'
instead of
driver = '{SQL Server}'
来源:https://stackoverflow.com/questions/42987940/geting-data-from-mssql-using-pyodbc-error