Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 997
Ben Nicholl Avatar asked Dec 14 '25 05:12

Ben Nicholl


1 Answers

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;[email protected]')
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.

like image 79
Tony Ju Avatar answered Dec 16 '25 19:12

Tony Ju



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!