Python使用Azure AD账号密码连接SQL Server

import pyodbc

# Some other example server values are

# server = 'localhost\sqlexpress' # for a named instance

# server = 'myserver,port' # to specify an alternate port



server = 'tcp:abc018.database.windows.net'

database = 'abc01'

username = 'HDOAS01@bib.com'

password = 'Z$PV27VjlQ'



cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server +';DATABASE='+database+';ENCRYPT=yes;UID='+username

+';Authentication=ActiveDirectoryPassword;PWD='+ password)

cursor = cnxn.cursor()



query="select name from sys.databases"

cursor.execute(query)

rows = cursor.fetchall()



print(rows)



Using Azure Active Directory with the ODBC Driver - ODBC Driver for SQL Server | Microsoft Learn




Name Values Default Description
Authentication (not set), (empty string), SqlPassword, ActiveDirectoryPassword, ActiveDirectoryIntegrated, ActiveDirectoryInteractive, ActiveDirectoryMsi, ActiveDirectoryServicePrincipal (not set) Controls the authentication mode.
Value Description
(not set) Authentication mode determined by other keywords (existing legacy connection options.)
(empty string) (Connection string only.) Override and unset an Authentication value set in the DSN.
SqlPassword Directly authenticate to a SQL Server instance using a username and password.
ActiveDirectoryPassword Authenticate with an Azure Active Directory identity using a username and password.
ActiveDirectoryIntegrated Windows, and Linux/Mac 17.6+, driver only. Authenticate with an Azure Active Directory identity using integrated authentication.
ActiveDirectoryInteractive Windows driver only. Authenticate with an Azure Active Directory identity using interactive authentication.
ActiveDirectoryMsi Authenticate with Azure Active Directory identity using managed identity authentication. For user-assigned identity, UID is set to the object ID of the user identity.
ActiveDirectoryServicePrincipal (17.7+) Authenticate with Azure Active Directory identity using service principal authentication. UID is set to the client ID of the service principal. PWD is set to the client secret.
Encrypt (not set), Yes/Mandatory(18.0+), No/Optional(18.0+), Strict(18.0+) (see description) Controls encryption for a connection. If the pre-attribute value of the Authentication setting isn't none in the DSN or connection string, the default is Yes. The default is also Yes in versions 18.0.1+. Otherwise, the default is No. If the attribute SQL_COPT_SS_AUTHENTICATION overrides the pre-attribute value of Authentication, explicitly set the value of Encryption in the DSN or connection string or connection attribute. The pre-attribute value of Encryption is Yes if the value is set to Yes in either the DSN or connection string.