Sqlalchemy-连接到Microsoft Azure-活动目录密码

时间:2019-06-13 13:50:20

标签: python sql-server sqlalchemy azure-sql-database

我使用bwlow代码通过sqlalchemy连接到MS SQL,现在它已迁移到Azure云。我尝试更改值代码,但我认为这不是连接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")

请注意,通过以下操作,我能够成功使用pyodbc进行连接,但无法通过sqlalchemy进行连接

enter link description here

请指导

1 个答案:

答案 0 :(得分:1)

我尝试了此代码,并使用Active Directory密码成功连接到我的Azure SQL数据库。

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)

用您的AD帐户替换UID

有关更多详细信息,请参阅此文档:Connecting to PyODBC

我的python版本是Python 3.7.3。

希望这会有所帮助。