python - 无法使用 Key Vault Secret 从 Python 连接 Azure SQL 数据库

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

我的 key 保管库 secret 是

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 key 连接到 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?谢谢。

最佳答案

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

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 中的 secret ,就可以解决该问题。

官方文档:

Connect SQL Server

关于python - 无法使用 Key Vault Secret 从 Python 连接 Azure SQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67682927/

相关文章:

python - django 'User' 对象没有属性 'user'

python - 检查嵌套字典内的成员资格

javascript - d3.js 从 url 获取 JSON

azure - SQL Azure 联合身份验证替代方案 : are Azure Queues or Service Bus Queues a good choice?

python - Numpy square 返回数组的错误值

Python Dataframe 列表 - 如何使数组中的元素数量相等

c# - 在 Azure 在线代码编辑器中构建机器人

c# - Redis StringSetAsync 在使用 Moq 的单元测试中返回 false

php - (Azure) MySQL : MySQL Server Has Gone Away

sql-server - 文件组中没有足够的空间来完成空文件操作