Connecting to SQL server from SQLAlchemy using odbc_connect

后端 未结 1 947
[愿得一人]
[愿得一人] 2021-01-06 04:28

I am new to Python and SQL server. I have been trying to insert a pandas df into our database for the past 2 days without any luck. Can anyone please help me debugging the e

相关标签:
1条回答
  • 2021-01-06 05:09

    As stated in the SQLAlchemy documentation, "The delimeters must be URL escaped" when using a pass-through exact pyodbc string.

    So, this will fail ...

    import pyodbc
    from sqlalchemy import create_engine
    
    params = r'DRIVER={SQL Server};SERVER=.\SQLEXPRESS;DATABASE=myDb;Trusted_Connection=yes'
    conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)
    engine = create_engine(conn_str)
    

    ... but this will work:

    import pyodbc
    from sqlalchemy import create_engine
    import urllib
    
    params = urllib.parse.quote_plus(r'DRIVER={SQL Server};SERVER=.\SQLEXPRESS;DATABASE=myDb;Trusted_Connection=yes')
    conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)
    engine = create_engine(conn_str)
    
    0 讨论(0)
提交回复
热议问题