Sqlalchemy - Connecting to Microsoft Azure - Active directory Password

安稳与你 提交于 2021-02-08 10:24:09

问题


I was connecting to MS SQL with sqlalchemy using bwlow code and now it has been migrated to azure cloud. I tried the chaging the values code but i think its not the proper way to connect ActiveDirectoryPassword

    import sqlalchemy
        from sqlalchemy import event, create_engine
# OLD connection string 
        engine = sqlalchemy.create_engine("mssql+pyodbc://" + "username" + ":" + "passkey" + "@" + "server" + "/" + "Database" + "?driver=SQL+Server"

        @event.listens_for(engine, 'before_cursor_execute')
        def receive_before_cursor_execute(conn, cursor, statement, params, context, executemany):
            if executemany:
                cursor.fast_executemany = True
                cursor.commit()

    # New connection string (for Active directory connection - not working)
    engine = sqlalchemy.create_engine("mssql+pyodbc://" + "abc@domain.com" + ":" + "passkey" + "@" + "xxxx-svsql1.database.windows.net" + "/" + "Database" + "?driver=SQL+Server" + "Authentication=ActiveDirectoryPassword")

Please note I was able to successfully able to connect using pyodbc but not able to do that using sqlalchemy by following

enter link description here

Please guide


回答1:


I tried this code and connect to my Azure SQL DATABASE with Active directory Password successfully.

import sqlalchemy
import urllib
import pyodbc
from sqlalchemy import event

params = urllib.parse.quote_plus("Driver={ODBC Driver 17 for SQL Server};Server=tcp:***.database.windows.net,1433;DATABASE=db_name;UID=***@***.com;PWD=***;Authentication=ActiveDirectoryPassword")
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)

@event.listens_for(engine, 'before_cursor_execute')
def receive_before_cursor_execute(conn, cursor, statement, params, context, executemany):
       if executemany:
            cursor.fast_executemany = True
            cursor.commit()

conn=engine.connect()
print(conn)

Replace the UID with your AD account.

For more details, please see the this document: Connecting to PyODBC.

My python version is Python 3.7.3.

Hope this helps.



来源:https://stackoverflow.com/questions/56582031/sqlalchemy-connecting-to-microsoft-azure-active-directory-password

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