Share via


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

此範例示範如何使用 Python 腳本中的 Azure SDK 管理連結庫來建立 適用於 MySQL 的 Azure 資料庫 彈性伺服器實例和資料庫。 它也提供簡單的腳本,以使用 mysql-connector 連結庫來查詢資料庫(不是 Azure SDK 的一部分)。 您可以使用類似的程式代碼來建立 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器實例和資料庫。

本文稍後會提供對等的 Azure CLI 命令 。 如果您想要使用 Azure 入口網站,請參閱建立 MySQL 伺服器建立 PostgreSQL 伺服器

本文中的所有命令在Linux/macOS bash和 Windows 命令殼層中都相同,除非另有說明。

1:設定本機開發環境

如果您尚未設定,請設定可在其中執行程式碼的環境。 以下列出一些選項:

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

使用下列內容建立名為 requirements.txt 的檔案:

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

在啟用虛擬環境的終端機中,安裝需求:

pip install -r requirements.txt

注意

在 Windows 上,嘗試將 mysql 連結庫安裝到 32 位 Python 連結庫會產生 mysql.h 檔案的相關錯誤。 在此情況下,請安裝 64 位版本的 Python,然後再試一次。

3:撰寫程式代碼以建立資料庫

使用下列程式代碼建立名為 provision_db.py 的 Python 檔案。 批註會說明詳細數據。 特別是,指定和PUBLIC_IP_ADDRESSAZURE_SUBSCRIPTION_ID環境變數。 后一個變數是工作站的IP位址,可供此範例執行。 您可以使用 WhatsIsMyIP 來尋找您的 IP 位址。

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"]

# Constants we need in multiple places: the resource group name and the region
# in which we provision resources. You can change these values however you want.
RESOURCE_GROUP_NAME = 'PythonAzureExample-DB-rg'
LOCATION = "southcentralus"

# 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

# We use a random number to create a reasonably unique database server name.
# If you've already provisioned a database and need to re-run the script, set
# the DB_SERVER_NAME environment variable to that name instead.
#
# Also set DB_USER_NAME and DB_USER_PASSWORD variables to avoid using the defaults.

db_server_name = os.environ.get("DB_SERVER_NAME", f"python-azure-example-mysql-{random.randint(1,100000):05}")
db_admin_name = os.environ.get("DB_ADMIN_NAME", "azureuser")
db_admin_password = os.environ.get("DB_ADMIN_PASSWORD", "ChangePa$$w0rd24")

# Obtain the management client object
mysql_client = MySQLManagementClient(credential, subscription_id)

# Provision the server and wait for the result
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.FIVE7
    )
)

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"]

# For the above code, create an environment variable named PUBLIC_IP_ADDRESS that
# contains your workstation's public IP address as reported by a site like
# https://whatismyipaddress.com/.

# 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 中指派適當的角色,以確保服務主體有足夠的許可權在訂用帳戶中建立資源群組和記憶體資源;例如,訂用帳戶上的參與者角色。

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

4:執行腳本

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

    az login
    
  2. AZURE_SUBSCRIPTION_ID設定和 PUBLIC_IP_ADDRESS 環境變數。 您可以執行 az account show 命令,從 id 輸出中的 屬性取得訂用帳戶識別碼。 您可以使用 WhatsIsMyIP 來尋找您的 IP 位址。

    set AZURE_SUBSCRIPTION_ID=00000000-0000-0000-0000-000000000000
    set PUBLIC_IP_ADDRESS=<Your public IP address>
    
  3. 選擇性地設定 DB_SERVER_NAMEDB_ADMIN_NAMEDB_ADMIN_PASSWORD 環境變數,否則會使用程式代碼預設值。

  4. 執行指令碼:

    python provision_db.py
    

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

使用下列程式代碼建立名為 use_db.py 的檔案。 請注意、 DB_ADMIN_NAMEDB_ADMIN_PASSWORD 環境變數的DB_SERVER_NAME相依性。 您可以從執行先前程式代碼provision_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", "azureuser")
db_admin_password = os.getenv("DB_ADMIN_PASSWORD", "ChangePa$$w0rd24")

db_name = os.getenv("DB_NAME", "example-db1")
db_port = os.getenv("DB_PORT", 3306)

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)。

接下來,下載透過 TSL/SSL 與 適用於 MySQL 的 Azure 資料庫 伺服器https://www.digicert.com/CACerts/BaltimoreCyberTrustRoot.crt.pem通訊所需的憑證,並將憑證檔案儲存至與 Python 檔案相同的資料夾。 如需詳細資訊,請參閱 適用於 MySQL 的 Azure 資料庫 檔中的取得 SSL 憑證

最後,執行程式代碼:

python use_db.py

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

6:清除資源

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

資源群組不會在您的訂用帳戶中產生任何持續費用,但資源群組中的資源,例如記憶體帳戶,可能會繼續產生費用。 最好清除您未主動使用的任何群組。 自 --no-wait 變數可讓命令立即傳回,而不是等待作業完成。

az group delete -n PythonAzureExample-DB-rg  --no-wait

您也可以使用 ResourceManagementClient.resource_groups.begin_delete 方法,從程式代碼中刪除資源群組。 範例:建立資源群組中的程式代碼會示範使用方式。

如需參考:對等的 Azure CLI 命令

下列 Azure CLI 命令會完成與 Python 腳本相同的布建步驟。 針對 PostgreSQL 資料庫,請使用 az postgres flexible-server 命令。

az group create --location southcentralus --name PythonAzureExample-DB-rg

az mysql flexible-server create --location southcentralus --resource-group PythonAzureExample-DB-rg ^
    --name python-azure-example-mysql-12345 --admin-user azureuser --admin-password ChangePa$$w0rd24 ^
    --sku-name Standard_B1ms --version 5.7 --yes

# Change the IP address to the public IP address of your workstation, that is, the address shown
# by a site like https://whatismyipaddress.com/.

az mysql flexible-server firewall-rule create --resource-group PythonAzureExample-DB-rg --name python-azure-example-mysql-12345 ^
    --rule-name allow_ip --start-ip-address 10.11.12.13 --end-ip-address 10.11.12.13

az mysql flexible-server db create --resource-group PythonAzureExample-DB-rg --server-name python-azure-example-mysql-12345 ^
    --database-name example-db1

另請參閱