简体   繁体   中英

connecting to sql-server via Python when authentication type is azure active directory

I am trying to see if it's possible to connect to SQL Server via Python when the authentication type is:

Azure Active Directory - Universal with MFA support

I can connect to this data base using Azure. The lines below show the credentials needed when connecting through azure data studio:

connection type : Microsoft SQL Server
server : ***.net
Authentication Type : Azure Active Directory - Universal with MFA support
account : ***.***@mycompany.com
database : target
Server group : default

I have looked everywhere on the web, and every thing I see regarding connecting to SQL Server via Python is when the Authentication Type is SQL login. Please help if you know the answer.

Yes, you can. Refer to this document for more details.

(Windows driver only.) AAD Interactive Authentication uses Azure Multi-factor Authentication technology to set up connection. In this mode, by providing the login ID, an Azure Authentication dialog is triggered and allows the user to input the password to complete the connection. The username is passed in the connection string.

server=Server;database=Database;UID=UserName;Authentication=ActiveDirectoryInteractive;

I have tested this on my side and my test code is as below.

import pyodbc
server = 'tonytest920.database.windows.net'
database = 'tonytest'
driver = '{ODBC Driver 17 for SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server +
                      ';PORT=1433;DATABASE='+database+';Authentication=ActiveDirectoryInteractive;UID=xx@xx.onmicrosoft.com')
cursor = cnxn.cursor()
cursor.execute(
    "select * from Persons")
row = cursor.fetchone()
while row:
    print(str(row[0]) + " " + str(row[1]))
    row = cursor.fetchone()

Note : You need to install adalsql.dll first. Remember to choose ENU\x86\adalsql.msi .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM