Building a connection URL for mssql+pyodbc with sqlalchemy.engine.url.URL

后端 未结 1 862
野性不改
野性不改 2021-02-04 19:22

The problem...

I am trying to connect to a MSSql server via SQLAlchemy. Here is my code with fake credentials (not my real credentials obviously).

T

相关标签:
1条回答
  • 2021-02-04 19:55

    As stated in the SQLAlchemy documentation, for mssql+pyodbc connections

    Hostname-based connections are not preferred, however are supported. The ODBC driver name must be explicitly specified:

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

    For

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

    your statement

    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']))
    

    produces the connect_url

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

    What you really need is

    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'))
    

    which produces

    mssql+pyodbc://scott:tiger@myhost:1560/databasename?driver=SQL+Server
    
    0 讨论(0)
提交回复
热议问题