Geting Data from MSSQL Using pyodbc Error

扶醉桌前 提交于 2019-12-11 02:31:57

问题


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:

  1. Normally, one supplies either the \INSTANCENAME or the port number, not both.
  2. ODBC connection strings for SQL Server do not use PORT=, they put the port number in the SERVER= 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!