【问题标题】:Sqlalchemy - Connecting to Microsoft Azure - Active directory PasswordSqlalchemy - 连接到 Microsoft Azure - 活动目录密码
【发布时间】:2019-10-28 03:19:26
【问题描述】:

我使用 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

请指导

【问题讨论】:

  • 您的问题现在解决了吗?如果我的回复对您有帮助,请将其标记为答案。谢谢!

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


【解决方案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)

UID 替换为您的 AD 帐户。

更多详情请看本文档:Connecting to PyODBC

我的 Python 版本是 Python 3.7.3。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 2016-08-05
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 2018-08-28
    相关资源
    最近更新 更多