使用服务主体连接Azure SQL Server

u4vypkhs  于 2022-12-24  发布在  SQL Server
关注(0)|答案(3)|浏览(163)

我想通过Python使用Azure服务主体连接Azure SQL数据库。
请帮帮我
我可以使用服务主体通过ADF连接它

0sgqnhkj

0sgqnhkj1#

有一个连接sql server的库Microsoft Azure Active Directory Authentication Library (ADAL) for Python,你可以从这里得到它。
在wiki文档中,你可以找到关于connecting to Azure SQL Database的教程。
你也可以参考这个article,它有连接服务器的详细步骤。

oymdgrw7

oymdgrw72#

我花了一些时间才弄明白这一点,所以我将在这里留下一些代码示例,以防对某些人有所帮助。
在我的例子中,我必须从Databricks连接到Synapse SQL Serverless。之前,我使用以下脚本安装了驱动程序"msodbcsql17":

%sh
#!/bin/bash
apt install unixodbc-dev
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
apt-get update
ACCEPT_EULA=Y apt-get install -y msodbcsql17

然后:
1.获取令牌:

from msal import ConfidentialClientApplication

creds = ConfidentialClientApplication(
    client_id='<your_client_id>', 
    authority='https://login.microsoftonline.com/<your_tenant_id>',
    client_credential= 'your_secret')

token = creds.acquire_token_for_client(scopes='https://database.windows.net//.default')

1.编码令牌(更多信息,请访问:https://www.linkedin.com/pulse/using-azure-ad-service-principals-connect-sql-from-python-andrade/):

import struct

SQL_COPT_SS_ACCESS_TOKEN = 1256 
tokenb = bytes(token["access_token"], "UTF-8")
exptoken = b'';
for i in tokenb:
    exptoken += bytes({i});
    exptoken += bytes(1);
tokenstruct = struct.pack("=i", len(exptoken)) + exptoken;

1.在pyodbc中,使用标记打开到数据库的连接并执行SQL语句:

import pyodbc

connString = 'DRIVER={ODBC Driver 17 for SQL Server};' \
             + 'SERVER=<your_server>;' \
              + 'DATABASE=<your_database>;'
conn = pyodbc.connect(connString, attrs_before = { SQL_COPT_SS_ACCESS_TOKEN:tokenstruct});

cursor = conn.cursor()
query="select name from sys.databases"
cursor.execute(query) 
row = cursor.fetchall()
xdnvmnnf

xdnvmnnf3#

看看这个教程:Lesson Learned #49: Does Azure SQL Database support Azure Active Directory connections using Service Principals?
本教程教我们使用Azure服务原理通过AAD连接Azure SQL数据库,并提供了Powershell和C#的示例代码。
我没有找到Python中的示例代码,我想这个教程可能对你有帮助,所以我想与你分享。
希望这个有用。

相关问题