共用方式為


範例:使用 Azure 連結庫建立資料庫

此範例示範如何使用適用於 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 CodeGitHub Codespaces中使用 開發容器

2:安裝所需的 Azure 連結庫套件

在此步驟中,您會安裝建立資料庫所需的 Azure SDK 連結庫。

  1. 在您的控制台中,建立 requirements.txt 檔案,其中列出此範例中使用的管理連結庫:

    azure-mgmt-resource
    azure-mgmt-rdbms
    azure-identity
    mysql-connector-python
    

    備註

    mysql-connector-python 程式庫不是 Azure SDK 的一部分。 這是第三方連結庫,可用來連線到 MySQL 資料庫。 您也可以使用 其他連結庫,例如 PyMySQLSQLAlchemy,來聯機到 MySQL 資料庫。

  2. 在已啟用虛擬環境的控制台中,安裝需求:

    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_Passwrod> # Change to your preferred admin password
export DB_NAME=<DB_Name> # Change to your preferred database name
export DB_PORT=3306
export version=ServerVersion.EIGHT0_21

4:撰寫程式代碼以使用資料庫建立及設定 MySQL 彈性伺服器

在此步驟中,您會使用下列程式代碼建立名為 provision_blob.py 的 Python 檔案。 此 Python 腳本會使用適用於 Python 的 Azure SDK 管理連結庫來建立資源群組、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://docs.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)。

如需 PostreSQL 資料庫伺服器,請參閱:

5:執行腳本

  1. 如果您尚未登入 Azure,請使用 Azure CLI 登入 Azure:

    az login
    
  2. 執行指令碼:

    python provision_db.py
    

    腳本需要一兩分鐘才能完成。

6:插入記錄並查詢資料庫

在此步驟中,您會在資料庫中建立數據表,並插入記錄。 您可以使用 mysql-connector 連結庫來連線到資料庫並執行 SQL 命令。

  1. 使用下列程式代碼建立名為 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='./BaltimoreCyberTrustRoot.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.connector API。 唯一的 Azure 特定部分是 MySQL 伺服器的完整主機網域(mysql.database.azure.com)。

  2. 接下來,下載透過 TSL/SSL 與適用於 MySQL 的 Azure 資料庫伺服器通訊所需的憑證。 如需詳細資訊,請參閱 Azure Database for MySQL 文件中的 取得 SSL 憑證 一節。

    #!/bin/bash
    # Download Baltimore CyberTrust Root certificate required for Azure MySQL SSL connections
    CERT_URL="https://www.digicert.com/CACerts/BaltimoreCyberTrustRoot.crt.pem"
    CERT_FILE="BaltimoreCyberTrustRoot.crt.pem"
    echo "Downloading SSL certificate..."
    curl -o "$CERT_FILE" "$CERT_URL"
    
  3. 最後,執行程式代碼:

    python use_db.py
    

如果您看到用戶端 IP 位址不允許的錯誤,請檢查您是否已正確定義環境變數 PUBLIC_IP_ADDRESS 。 如果您已使用錯誤的IP位址建立 MySQL 伺服器,您可以在 Azure 入口網站中新增另一個伺服器。 在入口網站中,選取 MySQL 伺服器,然後選取 [ 連線安全性]。 將工作站的IP位址新增至允許的IP位址清單。

7:清除資源

如果您不需要保留在此範例中建立的資源群組和記憶體資源,請執行 az group delete 命令。

資源群組不會在您的訂用帳戶中產生任何持續費用,但資源群組中的資源,例如記憶體帳戶,可能會繼續產生費用。 最好清除您未主動使用的任何群組。 --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
#!/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="5.7"

# 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."

另請參閱