Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use pyodbc.connect() with authorization=ActiveDirectoryIntegrated?

Trying to access Azure SQL through a python function in VS code, with Authentication set to Active Directory Integrated. Using pyodbc to connect.

Works fine when run locally but get an error after deploying to Azure. Also works fine if I use SQL login but I want to use Active Directory Integrated. I have already set myself as an AD admin.

What I am trying:

cnxn = pyodbc.connect("Driver={ODBC Driver 17 for SQL Server};Server=tcp:khawajaserver1.database.windows.net,1433;Database=KhawajaDB1;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;Authentication=ActiveDirectoryIntegrated")

Error I get:

Result: Failure
Exception: Error: ('HY000', '[HY000] [Microsoft][ODBC Driver 17 for SQL Server]MAX_PROVS: Error code 0x57 (87) (SQLDriverConnect)')
Stack:   File "/usr/local/lib/python3.6/site-packages/azure/functions_worker/dispatcher.py", line 308, in _handle__invocation_request
like image 846
Khawaja Avatar asked Nov 01 '25 04:11

Khawaja


2 Answers

I know Active Directory Password as authentication type works.

db_list = [TEST_DB1, TEST_DB2]
sql_conn = None
for db in db_list:
    try:
        conn_string = 'DRIVER={ODBC Driver 17 for SQL Server};' \
                      'SERVER=' + <db_url> + \
                      ';DATABASE=' + <db_name> + \
                      ';UID=' + <db_username> + \
                      ';PWD=' + <db_password> + \
                      ';Authentication=ActiveDirectoryPassword'
        print conn_string
        sql_conn = pyodbc.connect(conn_string)
except Exception as e:
    print "Exception:::", e
    print 'Cannot connect to DB' + str(sys.exc_info()[0])
    return None
sql_conn.cursor().execute(<some SQL Query>)
sql_conn.close()
like image 93
Alberto Morillo Avatar answered Nov 02 '25 18:11

Alberto Morillo


The following code worked for me

# Connection to SQL Server using AADIntegrated

import pyodbc 

server = 'data1.database.windows.net' 
database = 'MyTestDB' 
authentication = 'ActiveDirectoryIntegrated'
kpi_server_connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';Authentication='+authentication+';TrustServerCertificate='+ 'no')

query_string = '''
    select top 10 * from [SomeTable] 
    '''
df = pd.read_sql(query_string, kpi_server_connection)
df
like image 35
Vikas Singh Avatar answered Nov 02 '25 19:11

Vikas Singh



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!