【问题标题】:Unable to connect Azure SQL database from Python using Key Vault Secret无法使用 Key Vault Secret 从 Python 连接 Azure SQL 数据库
【发布时间】:2021-05-25 06:42:29
【问题描述】:

我的 Key Vault 机密是

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

我可以使用来自 Azure ADF 的上述 KV 密码连接到 Azure SQL 数据库。 我正在尝试通过 Python 代码做同样的事情:

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()

但代码失败并出现以下错误:

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)')

您能帮我在 KV 中进行哪些更改或 Azure 仍然不支持 Python KV?谢谢。

【问题讨论】:

    标签: python azure azure-sql-database pyodbc azure-keyvault


    【解决方案1】:

    你的连接字符串应该如下所示。

    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;
    

    我相信如果你改变 kv 中的秘密,你可以解决这个问题。

    官方文档:

    Connect SQL Server

    【讨论】:

    • 谢谢杰森。我知道连接字符串。我正在尝试使用 Azure Key Vault 机密连接到 Azure SQL。
    猜你喜欢
    • 1970-01-01
    • 2020-09-09
    • 2021-04-29
    • 2018-07-19
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多