本文介绍了Sqlalchemy-连接到Microsoft Azure-Active Directory密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用bwlow代码通过sqlalchemy连接到MS SQL,现在它已迁移到Azure云.我尝试过修改值代码,但我认为它不是连接ActiveDirectoryPassword的正确方法

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")

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

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

输入链接描述这里

请指导

推荐答案

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

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)

用您的AD帐户替换 UID .

有关更多详细信息,请参阅此文档:连接到PyODBC .

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

我的python版本是Python 3.7.3.

My python version is Python 3.7.3.

希望这会有所帮助.

这篇关于Sqlalchemy-连接到Microsoft Azure-Active Directory密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 13:09