Unable to connect Azure SQL database from Python using Key Vault Secret

Viewed 694

My Key vault secret is

integrated security=False;encrypt=True;connection timeout=30;data source=yyy.database.windows.net;initial catalog=db-xxxx;user id=xx-user;password=pwd-xx

I am able to connect to Azure SQL database using the above KV secret from Azure ADF. I am trying to do the same thru Python code:

from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
import pyodbc

KVUri = "https://yyy-kv.vault.azure.net/"

credential = DefaultAzureCredential()
client = SecretClient(vault_url=KVUri, credential=credential)
secretName = "xxxx"
print("Retrieving your secret")
retrieved_secret = client.get_secret(secretName)
print(f"Your secret is '{retrieved_secret.value}'.")
print(" done.")
# The code fails after this.
with pyodbc.connect(retrieved_secret.value) as conn:
    with conn.cursor() as cursor:
        cursor.execute("SELECT TOP 3 name, collation_name FROM sys.databases")
        row = cursor.fetchone()
        while row:
            print (str(row[0]) + " " + str(row[1]))
            row = cursor.fetchone()

But the code fails with the below error :

Traceback (most recent call last):
  File "first.py", line 25, in <module>
    with pyodbc.connect(retrieved_secret.value) as conn:
pyodbc.InterfaceError: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnect)')

Can you help me what changes I have to do in KV or still Azure does not support Python KV? Thanks.

1 Answers

You connection string should be like below.

Driver={ODBC Driver 17 for SQL Server};Server=yy.database.windows.net,1433;Database=dbname;Uid=sasasa;Pwd={pwd};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;

I believe if you change the secret in kv, you can fix the issue.

Offical doc:

Connect SQL Server

Related