如何使用 Active Directory 集成身份验证通过 python SQL alchemy 连接到 sql azure 数据库

How to connect to the sql azure database with python SQL alchemy using active directory integrated authentication

我正在使用如下连接字符串

params=parse.quote_plus("Driver={ODBC Driver 17 For SQL server};Server=tcp:server name,1433;database=database name;Encrypt=yes;TrustServerCertificate=no;Authentication=ActiveDirectoryIntegrated'
engine=sqlalchemy.create_engine("mssql:///?odbc_connect=%s" %params)

使用上面的连接字符串时出现错误

[Microsoft][ODBC Driver 17 for SQL server][SQL server]111214 an attempt to an attempt to complete the transaction has failed no corresponding transaction found 

更新

您可以添加connect_args,然后尝试。

请确保您使用相同的帐户登录您的 windows 电脑和 sql 服务器。

engine = create_engine('mssql+pyodbc:///?odbc_connect=%s' % params, echo=True, connect_args={'autocommit': True})

上一个

你可以考虑使用Authentication=ActiveDirectoryPassword,它比Authentication=ActiveDirectoryIntegrated更简单,下面的代码对我来说是可行的。

感谢Peter Pan的回答,更多的细节可以参考他的描述。他的回答里有详细描述Authentication=ActiveDirectoryIntegrated的用法,我更喜欢Authentication=ActiveDirectoryPassword,所以贴出我的回答,大家可以参考。

from urllib import parse
from sqlalchemy import create_engine

your_user_name = 'pa**i@**a.onmicrosoft.com'
your_password_here = 'J***20'
connecting_string = 'Driver={ODBC Driver 17 for SQL Server};Server=tcp:yoursqlserver.database.windows.net,1433;Database=yoursqldb;Uid='+your_user_name+';Pwd='+your_password_here+';Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;Authentication=ActiveDirectoryPassword'
params = parse.quote_plus(connecting_string)

engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
connection = engine.connect()
result = connection.execute("select 1+1 as res")
for row in result:
    print("res:", row['res'])
connection.close()