azure - 使用 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
)
解决方案
我们可以使用 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()
希望这可以帮助。
推荐阅读
- android - 泄露的 ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient
- java - 用 Java 编码到 Factorial 23
- java - 为什么我不能从文件创建 TreeSet 对象?
- vba - 在 VBA 中调用 RFC_READ_TABLE 期间出现错误 61704
- azure-machine-learning-studio - Python 中的 Azure ML SDK,要集成到 Notebook 中的 Azure ML 模型
- python - 将大文件加载到内存(持久)
- visual-studio-code - VS Code:在未选择文本的情况下选择或删除块注释的快捷方式
- dialogflow-es - 如果话语不作为精确的训练短语存在,则实体值是整个话语
- reactjs - 如何在 React.js 中触发动画?“TypeError:无法读取未定义的属性‘startAnimation’”
- c# - DI 的继承工作很奇怪