简体   繁体   中英

Sqlalchemy - Connecting to Microsoft Azure - Active directory Password

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM