使用sqlalchemy.engine.url.URL为mssql + pyodbc构建连接URL

时间:2017-09-06 22:54:51

标签: python sql-server sqlalchemy connection-string pyodbc

问题......

我正在尝试通过SQLAlchemy连接到MSSql服务器。这是我的代码与假证书(显然不是我真正的凭据)。

代码......

credentials = {
'username'  : 'SPOTTER_xyz_ACC',
'password'  : '123Goodbye2016!@#',
'host'      : 'MARYLQLT01',
'database'  : 'LRS_DUS',
'port'      : '1560'}

connect_url = sqlalchemy.engine.url.URL(
    'mssql+pyodbc',
    username=credentials['username'],
    password=credentials['password'],
    host=credentials['host'],
    port=credentials['port'],
    query=dict(service_name=credentials['database']))

engine = create_engine(connect_url)
connection=engine.connect()

这是我得到的.pyodbc错误。

(pyodbc.Error) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source
name not found and no default driver specified (0) (SQLDriverConnect)')

其他详细信息

但是,这是奇怪的...我如果做一个pyodbc连接并使用Pandas.read_sql,那么我可以获得没有错误的数据。所以我不明白为什么我得到'pyodbc'错误????

connection=pyodbc.connect(\
                          'Driver={SQL Server}; \
                          Server=MARYLQLT01; \
                          Database=LRS_DUS; \
                          UID=SPOTTER_xyz_ACC; \
                          PWD=123Goodbye2016!@#')

stmt='select * from PD_SC_All'
df=pd.read_sql(stmt,connection)

然后我可以看到数据帧。

那么,当我尝试连接SQLAlchemy时,为什么会得到(pyodbc.Error)

系统信息

Windows 7
SQLAlchemy: 1.1.11
pyodbc: 4.0.16

Python 3.6.1 |Anaconda custom (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 5.3.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

1 个答案:

答案 0 :(得分:8)

SQLAlchemy documentation中所述,适用于mssql+pyodbc个连接

  

基于主机名的连接不首选,但受支持。必须明确指定ODBC驱动程序名称:

engine = create_engine("mssql+pyodbc://scott:tiger@myhost:port/databasename?driver=SQL+Server+Native+Client+10.0")

对于

credentials = {
    'username': 'scott',
    'password': 'tiger',
    'host': 'myhost',
    'database': 'databasename',
    'port': '1560'}

你的陈述

connect_url = sqlalchemy.engine.url.URL(
    'mssql+pyodbc',
    username=credentials['username'],
    password=credentials['password'],
    host=credentials['host'],
    port=credentials['port'],
    query=dict(service_name=credentials['database']))

生成connect_url

mssql+pyodbc://scott:tiger@myhost:1560?service_name=databasename

你真正需要的是

connect_url = sqlalchemy.engine.url.URL(
    'mssql+pyodbc',
    username=credentials['username'],
    password=credentials['password'],
    host=credentials['host'],
    port=credentials['port'],
    database=credentials['database'],
    query=dict(driver='SQL+Server'))

产生

mssql+pyodbc://scott:tiger@myhost:1560/databasename?driver=SQL+Server