首页 > 解决方案 > 使用 Python 通过 Azure AD 查询 Azure SQL 数据库

问题描述

import pyodbc
server = '<server>.database.windows.net'
database = '<database>'
username = '<username>'
password = '<password>'
driver= '{ODBC Driver 17 for SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName FROM [SalesLT].[ProductCategory] pc JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid")
row = cursor.fetchone()
while row:
    print (str(row[0]) + " " + str(row[1]))
    row = cursor.fetchone()

我只看到有一个用户名&&密码凭据允许我现在连接到 Azure SQL 数据库。

有一种方法可以让我使用 Azure AD 凭据连接到 SQL 数据库吗?例如我想使用 device_code_credentials

device_code_credentials = DeviceCodeCredential(client_id, tenant_id=tenant_id, authority=authority_host_uri)

我可以使用此凭据调用 blob 服务客户端,并且想知道 Python SDK 中是否有一种简单的方法可以连接到 Azure SQL 数据库。

blob_service_client = BlobServiceClient(
   account_url=self.url,
   credential=self.credential
)

标签: azureazure-active-directoryazure-sql-database

解决方案


我们可以使用 Azure AD 身份验证连接到 Azure SQL 数据库。

在 Portal 上获取 AD Active Directory 密码认证: 在此处输入图像描述

Python代码示例:

import pyodbc

server = 'your_server.database.windows.net'
database = 'your_database'
username = 'your_username'
password = 'your_password'
driver= '{ODBC Driver 17 for SQL Server}'
Authentication='ActiveDirectoryPassword'

cnxn = pyodbc.connect(
    'DRIVER='+driver+
    ';PORT=1433;SERVER='+server+
    ';PORT=1443;DATABASE='+database+
    ';UID='+username+
    ';PWD='+ password+
    ';Authentication='+Authentication)

cursor = cnxn.cursor()

cursor.execute("SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName FROM [SalesLT].[ProductCategory] pc JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid")
row = cursor.fetchone()
while row:
    print (str(row[0]) + " " + str(row[1]))
    row = cursor.fetchone()

希望这可以帮助。


推荐阅读