Awknewbie
Awknewbie

Reputation: 269

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://" + "[email protected]" + ":" + "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

Upvotes: 1

Views: 7381

Answers (1)

Leon Yue
Leon Yue

Reputation: 16411

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.

Upvotes: 9

Related Questions