SQLAlchemy PyODBC MS SQL Server DSN-less connection

那年仲夏 提交于 2019-12-12 21:56:53

问题


Using python 2.7 and the MS odbc driver through pyodbc. My connection string looks like this:

mssql+pyodbc://myuser:mypass@serverip/instancename?driver=ODBC+Driver+11+for+SQL+Server

I am getting login failed. However if I use the same credentials and "serverip\instancename" in the microsoft sql server management studio, I can connect.

The thing that is driving me crazy is a couple of days ago, this same connection string worked for me but to a different sql server instance on the same machine. So what I am trying to figure out is how to go about troubleshooting it.

Thanks for any pointers.


回答1:


I just went through this, the reason it fails is the port, each instance listens in a different port, so you need to point which port is for that instance.

my code is:

DBserver='host.abc.nt'
DBengine='devenv'
DBport='####'
DBname='mydb'
DBDriver='ODBC Driver 13 for SQL Server'
DBuser='user'
DBpwd='pass'
DBuserpass = DBuser if len(DBuser) > 0 else ''
DBuserpass = DBuserpass + ':' + DBpwd if len(DBuser) > 0 else ''
if len(DBengine) > 0:
    DBserver = DBserver + '\\' + DBengine 

engine = sa.create_engine(f'''mssql+pyodbc://{DBuserpass}@{DBserver}:{DBport}/{DBname}?driver={DBDriver}''')

query=engine.execute('SELECT DB_NAME(), @@SERVERNAME')
query.fetchall()
[('mydb', 'host\\devenv')]

With that you create the engine, there is no need for other libraries besides sqlalchemy

but if you want to know the port of the instance, you can use: Github repository from gordthompson/sqlserverport

or in Windows you connect with SQL Studio (or anything else) do some selects the the DB and in the meanwhile in CMD run a netstat to get the port:

C:\Users\pla>netstat -qfa | findstr host
 TCP    10.0.0.1:##87     host.abc.nt:4096  ESTABLISHED



回答2:


When learning sqlalchemy I had the same issue. This method worked for me:

import urllib
params = urllib.quote_plus("DRIVER={SQL Server Native Client 10.0};SERVER=dagger;DATABASE=test;UID=user;PWD=password")

engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)

Which comes from the sqlalchemy documentation. It does not seem related to the login credentials, but the error message was the same for me and this worked.

ref http://docs.sqlalchemy.org/en/latest/dialects/mssql.html#pass-through-exact-pyodbc-string



来源:https://stackoverflow.com/questions/30363348/sqlalchemy-pyodbc-ms-sql-server-dsn-less-connection

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