此範例示範如何使用適用於 Python 的 Azure SDK 管理連結庫,以程式設計方式建立適用於 MySQL 的 Azure 資料庫彈性伺服器和對應的資料庫。 它還包含一個腳本,利用mysql-connector-python函式庫(非 Azure SDK 的一部分)連接並查詢資料庫。
您可以藉由修改相關的 SDK 匯入和 API 呼叫,調整此範例來建立適用於 PostgreSQL 的 Azure 資料庫彈性伺服器。
如果您想要使用 Azure CLI,本文稍後會提供 對等的 Azure CLI 命令 。 如需圖形化體驗,請參閱 Azure 入口網站檔:
除非另有說明,本文中所有範例與指令在 Linux/macOS bash 與 Windows 指令殼層間都能穩定運作。
1:設定本機開發環境
如果您尚未設定,請設定可在其中執行程式碼的環境。 以下是一些選項:
使用
venv或您選擇的工具設定 Python 虛擬環境。 若要開始使用虛擬環境,請務必加以啟用。 若要安裝 Python,請參閱 安裝 Python。#!/bin/bash # Create a virtual environment python -m venv .venv # Activate the virtual environment source .venv/Scripts/activate # only required for Windows (Git Bash)使用 conda 的環境。 若要安裝 Conda,請參閱 安裝 Miniconda。
在 Visual Studio Code 或 GitHub Codespaces中使用 開發容器。
2:安裝所需的 Azure 連結庫套件
在此步驟中,您會安裝建立資料庫所需的 Azure SDK 連結庫。
在您的控制台中,建立 requirements.txt 檔案,其中列出此範例中使用的管理連結庫:
azure-mgmt-resource azure-mgmt-rdbms azure-identity mysql-connector-python備註
mysql-connector-python程式庫不是 Azure SDK 的一部分。 這是一個第三方函式庫,可以用來連接 MySQL 資料庫。 你也可以使用其他函式庫,例如PyMySQL或SQLAlchemy。在已啟用虛擬環境的控制台中,安裝需求:
pip install -r requirements.txt備註
在 Windows 上,嘗試將 mysql 連結庫安裝到 32 位 Python 連結庫會產生 mysql.h 檔案的相關錯誤。 在此情況下,請安裝 64 位版本的 Python,然後再試一次。
3.設定環境變數
在此步驟中,您會設定環境變數以用於本文中的程序代碼。 程序代碼會使用os.environ方法來擷取值。
#!/bin/bash
export AZURE_RESOURCE_GROUP_NAME=<ResourceGroupName> # Change to your preferred resource group name
export LOCATION=<Location> # Change to your preferred region
export AZURE_SUBSCRIPTION_ID=$(az account show --query id --output tsv)
export PUBLIC_IP_ADDRESS=$(curl -s https://api.ipify.org)
export DB_SERVER_NAME=<DB_Server_Name> # Change to your preferred DB server name
export DB_ADMIN_NAME=<DB_Admin_Name> # Change to your preferred admin name
export DB_ADMIN_PASSWORD=<DB_Admin_Password> # Change to your preferred admin password
export DB_NAME=<DB_Name> # Change to your preferred database name
export DB_PORT=3306
export DB_SERVER_VERSION=EIGHT0_21
4:撰寫程式代碼以使用資料庫建立及設定 MySQL 彈性伺服器
在此步驟中,你會建立一個名為 provision_db.py 的Python檔案,程式碼如下。 這個腳本使用 Azure SDK for Python 管理函式庫,建立資源群組、MySQL 靈活伺服器,以及該伺服器上的資料庫。
import random, os
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.rdbms.mysql_flexibleservers import MySQLManagementClient
from azure.mgmt.rdbms.mysql_flexibleservers.models import Server, ServerVersion
# Acquire a credential object using CLI-based authentication.
credential = DefaultAzureCredential()
# Retrieve subscription ID from environment variable
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
# Retrieve resource group name and location from environment variables
RESOURCE_GROUP_NAME = os.environ["AZURE_RESOURCE_GROUP_NAME"]
LOCATION = os.environ["LOCATION"]
# Step 1: Provision the resource group.
resource_client = ResourceManagementClient(credential, subscription_id)
rg_result = resource_client.resource_groups.create_or_update(RESOURCE_GROUP_NAME,
{ "location": LOCATION })
print(f"Provisioned resource group {rg_result.name}")
# For details on the previous code, see Example: Provision a resource group
# at https://learn.microsoft.com/azure/developer/python/azure-sdk-example-resource-group
# Step 2: Provision the database server
# Retrieve server name, admin name, and admin password from environment variables
db_server_name = os.environ.get("DB_SERVER_NAME")
db_admin_name = os.environ.get("DB_ADMIN_NAME")
db_admin_password = os.environ.get("DB_ADMIN_PASSWORD")
# Obtain the management client object
mysql_client = MySQLManagementClient(credential, subscription_id)
# Provision the server and wait for the result
server_version = os.environ.get("DB_SERVER_VERSION")
poller = mysql_client.servers.begin_create(RESOURCE_GROUP_NAME,
db_server_name,
Server(
location=LOCATION,
administrator_login=db_admin_name,
administrator_login_password=db_admin_password,
version=ServerVersion[server_version] # Note: dictionary-style enum access
)
)
server = poller.result()
print(f"Provisioned MySQL server {server.name}")
# Step 3: Provision a firewall rule to allow the local workstation to connect
RULE_NAME = "allow_ip"
ip_address = os.environ["PUBLIC_IP_ADDRESS"]
# Provision the rule and wait for completion
poller = mysql_client.firewall_rules.begin_create_or_update(RESOURCE_GROUP_NAME,
db_server_name, RULE_NAME,
{ "start_ip_address": ip_address, "end_ip_address": ip_address }
)
firewall_rule = poller.result()
print(f"Provisioned firewall rule {firewall_rule.name}")
# Step 4: Provision a database on the server
db_name = os.environ.get("DB_NAME", "example-db1")
poller = mysql_client.databases.begin_create_or_update(RESOURCE_GROUP_NAME,
db_server_name, db_name, {})
db_result = poller.result()
print(f"Provisioned MySQL database {db_result.name} with ID {db_result.id}")
程式代碼中的驗證
在本文後面,你要使用 Azure CLI 來執行範例程式碼來登入 Azure。 如果你的帳號有足夠權限在 Azure 訂閱中建立資源群組和資料庫資源,腳本就能順利執行,無需額外設定。
對於生產環境,請使用服務主體進行認證並設定適當的環境變數。 此方法可以啟用安全、非互動式的存取,非常適合用於自動化。 如需設定指示,請參閱 如何使用 Azure 服務驗證 Python 應用程式。
確保服務主體被分配到具備足夠權限的角色,例如訂閱或資源群組層級的貢獻者角色。 關於角色指派的詳細資訊,請參閱 Azure 中的角色基礎存取控制(RBAC)。
程式代碼中使用的類別參考連結
- ResourceManagementClient (azure.mgmt.resource)
- MySQLManagementClient (azure.mgmt.rdbms.mysql_flexibleservers)
- 伺服器(azure.mgmt.rdbms.mysql_flexibleservers.models)
- ServerVersion (azure.mgmt.rdbms.mysql_flexibleservers.models)
關於 PostgreSQL 資料庫伺服器,請參見:
5:執行腳本
如果你還沒登入,請使用以下Azure CLI登入Azure:
az login執行指令碼:
python provision_db.py腳本需要一兩分鐘才能完成。
6:插入記錄並查詢資料庫
在此步驟中,您會在資料庫中建立數據表,並插入記錄。 使用 mysql-connector 函式庫連接資料庫並執行 SQL 指令。
使用下列程式代碼建立名為 use_db.py 的檔案。
這段程式碼只適用於 MySQL。 你會用不同的 PostgreSQL 函式庫。
import os import mysql.connector db_server_name = os.environ["DB_SERVER_NAME"] db_admin_name = os.getenv("DB_ADMIN_NAME") db_admin_password = os.getenv("DB_ADMIN_PASSWORD") db_name = os.getenv("DB_NAME") db_port = os.getenv("DB_PORT") connection = mysql.connector.connect(user=db_admin_name, password=db_admin_password, host=f"{db_server_name}.mysql.database.azure.com", port=db_port, database=db_name, ssl_ca='./DigiCertGlobalRootG2.crt.pem') cursor = connection.cursor() """ # Alternate pyodbc connection; include pyodbc in requirements.txt import pyodbc driver = "{MySQL ODBC 5.3 UNICODE Driver}" connect_string = f"DRIVER={driver};PORT=3306;SERVER={db_server_name}.mysql.database.azure.com;" \ f"DATABASE={DB_NAME};UID={db_admin_name};PWD={db_admin_password}" connection = pyodbc.connect(connect_string) """ table_name = "ExampleTable1" sql_create = f"CREATE TABLE {table_name} (name varchar(255), code int)" cursor.execute(sql_create) print(f"Successfully created table {table_name}") sql_insert = f"INSERT INTO {table_name} (name, code) VALUES ('Azure', 1)" insert_data = "('Azure', 1)" cursor.execute(sql_insert) print("Successfully inserted data into table") sql_select_values= f"SELECT * FROM {table_name}" cursor.execute(sql_select_values) row = cursor.fetchone() while row: print(str(row[0]) + " " + str(row[1])) row = cursor.fetchone() connection.commit()這些程式碼全都使用
mysql.connectorAPI。 唯一 Azure 專屬的部分是 MySQL 伺服器的完整主機域(mysql.database.azure.com)。接著,下載用 TLS/SSL 與 適用於 MySQL 的 Azure 資料庫 伺服器通訊所需的根憑證。 Azure MySQL 彈性伺服器使用 DigiCert Global Root G2 證書。 欲了解更多資訊,請參閱 Connect to 適用於 MySQL 的 Azure 資料庫 - 具備加密連線的彈性伺服器。
#!/bin/bash # Download DigiCert Global Root G2 certificate required for Azure MySQL SSL connections CERT_URL="https://cacerts.digicert.com/DigiCertGlobalRootG2.crt.pem" CERT_FILE="DigiCertGlobalRootG2.crt.pem" echo "Downloading SSL certificate..." curl -o "$CERT_FILE" "$CERT_URL"最後,執行程式代碼:
python use_db.py
如果您看到用戶端 IP 位址不允許的錯誤,請檢查您是否已正確定義環境變數 PUBLIC_IP_ADDRESS 。 如果您已使用錯誤的IP位址建立 MySQL 伺服器,您可以在 Azure 入口網站中新增另一個伺服器。 在入口網站中,選擇 MySQL 伺服器,然後選擇網路。 將工作站的IP位址新增至允許的IP位址清單。
7:清除資源
如果你不需要保留這個範例中建立的資源群組和資料庫資源,請執行 az 群組刪除 指令。
資源群組不會在您的訂用帳戶中產生任何持續費用,但資源群組中的資源可能會繼續產生費用。 最好清除您未主動使用的任何群組。
--no-wait 自變數可讓命令立即傳回,而不是等待作業完成。
#!/bin/bash
az group delete -n $AZURE_RESOURCE_GROUP_NAME --no-wait
您也可以使用 ResourceManagementClient.resource_groups.begin_delete 方法,從程式代碼中刪除資源群組。
範例:建立資源群組中的程式代碼會示範使用方式。
如需參考:對等的 Azure CLI 命令
下列 Azure CLI 命令會完成與 Python 腳本相同的布建步驟。 針對 PostgreSQL 資料庫,請使用 az postgres flexible-server 命令。
#!/bin/bash
# Set variables
export LOCATION=<Location> # Change to your preferred region
export AZURE_RESOURCE_GROUP_NAME=<ResourceGroupName> # Change to your preferred resource group name
export DB_SERVER_NAME=<DB_Server_Name> # Change to your preferred DB server name
export DB_ADMIN_NAME=<DB_Admin_Name> # Change to your preferred admin name
export DB_ADMIN_PASSWORD=<DB_Admin_Password> # Change to your preferred admin password
export DB_NAME=<DB_Name> # Change to your preferred database name
export DB_SERVER_VERSION="8.4"
# Get public IP address
export PUBLIC_IP_ADDRESS=$(curl -s https://api.ipify.org)
# Provision the resource group
echo "Creating resource group: $AZURE_RESOURCE_GROUP_NAME"
az group create \
--location "$LOCATION" \
--name "$AZURE_RESOURCE_GROUP_NAME"
# Provision the MySQL Flexible Server
echo "Creating MySQL Flexible Server: $DB_SERVER_NAME"
az mysql flexible-server create \
--location "$LOCATION" \
--resource-group "$AZURE_RESOURCE_GROUP_NAME" \
--name "$DB_SERVER_NAME" \
--admin-user "$DB_ADMIN_NAME" \
--admin-password "$DB_ADMIN_PASSWORD" \
--sku-name Standard_B1ms \
--version "$DB_SERVER_VERSION" \
--yes
# Provision a firewall rule to allow access from the public IP address
echo "Creating firewall rule for public IP: $PUBLIC_IP_ADDRESS"
az mysql flexible-server firewall-rule create \
--resource-group "$AZURE_RESOURCE_GROUP_NAME" \
--name "$DB_SERVER_NAME" \
--rule-name allow_ip \
--start-ip-address "$PUBLIC_IP_ADDRESS" \
--end-ip-address "$PUBLIC_IP_ADDRESS"
# Provision the database
echo "Creating database: $DB_NAME"
az mysql flexible-server db create \
--resource-group "$AZURE_RESOURCE_GROUP_NAME" \
--server-name "$DB_SERVER_NAME" \
--database-name "$DB_NAME"
echo "MySQL Flexible Server and database created successfully."