共用方式為


快速入門:使用 Python 連線並查詢適用於 PostgreSQL 的 Azure 資料庫中的資料

在本快速入門中,您將使用 Python 連線至適用於 PostgreSQL 的 Azure 資料庫彈性伺服器執行個體。 接著,您將在 macOS、Ubuntu Linux 和 Windows 平台上使用 SQL 陳述式,在資料庫中進行查詢、插入、更新和刪除資料。

本文中的步驟包含兩種驗證方法:Microsoft Entra 驗證與 PostgreSQL 驗證。 [無密碼] 索引標籤會顯示 Microsoft Entra 驗證,而 [密碼] 索引標籤則會顯示 PostgreSQL 驗證。

Microsoft Entra 驗證是一種機制,會使用 Microsoft Entra ID 中所定義的身分識別以連線到適用於 PostgreSQL 的 Azure 資料庫。 透過 Microsoft Entra 驗證,您可以在集中的位置管理資料庫使用者的身分識別和其他 Microsoft 服務,從而簡化權限管理。 若要深入瞭解,請參閱使用 適用於 PostgreSQL 的 Azure 資料庫進行 Microsoft Entra 驗證

PostgreSQL 驗證會使用儲存在 PostgreSQL 中的帳戶。 若您選擇使用密碼作為帳戶的認證,這些認證將會儲存在 user 資料表中。 由於這些密碼會儲存在 PostgreSQL 中,因此您必須自行管理密碼的輪替。

本文假設您熟悉使用 Python 進行開發,但您不熟悉使用適用於 PostgreSQL 的 Azure 資料庫。

先決條件

為您的用戶端工作站新增防火牆規則

  • 如果您在建立適用於 PostgreSQL 的 Azure 資料庫彈性伺服器執行個體時選擇了私人存取 (虛擬網路整合),則必須從與伺服器相同虛擬網路內的資源連線至伺服器。 您可以建立虛擬機器,並將其新增至建立適用於 PostgreSQL 的 Azure 資料庫彈性伺服器執行個體時所產生的虛擬網路中。 請參閱 網路
  • 如果您在建立適用於 PostgreSQL 的 Azure 資料庫彈性伺服器執行個體時選擇了公用存取 (允許的 IP 位址),則可以將您的本機 IP 位址新增至伺服器的防火牆規則清單。 請參閱 網路

在伺服器上設定 Microsoft Entra 整合 (僅限無密碼)

如果您要遵循無密碼驗證的步驟,必須為伺服器執行個體設定 Microsoft Entra 驗證,且您必須被指派為該伺服器執行個體的 Microsoft Entra 管理員。 請遵循設定 Microsoft Entra 整合中的步驟,以確保已設定 Microsoft Entra 驗證,且您已獲指派為伺服器執行個體的 Microsoft Entra 管理員。

準備開發環境

切換至您要執行程式碼的資料夾,並建立及啟動虛擬環境。 虛擬環境是一個獨立的目錄,其中包含特定版本的 Python,以及該應用程式所需的其他套件。

執行下列命令來建立並啟動虛擬環境:

py -3 -m venv .venv
.venv\Scripts\activate

安裝 Python 程式庫

安裝執行程式碼範例所需的 Python 程式庫。

安裝 azure-identity 程式庫,此程式庫為整個 Azure SDK 提供 Microsoft Entra 權杖驗證支援。

# Use the interpreter-bound pip to ensure installs go into the active venv/interpreter
python -m pip install --upgrade pip
python -m pip install azure-identity azure-keyvault-secrets

新增驗證程式碼

在本節中,您將在工作目錄中新增驗證程式碼,並執行對伺服器執行個體進行驗證與授權時所需的任何其他步驟。

在新增驗證程式碼之前,請確保已安裝每個範例所需的套件。

必要套件 (本文範例):

  • 無密碼範例:azure-identityazure-keyvault-secrets (如果您使用 Key Vault)
  • 密碼範例:psycopg (建議:python -m pip install "psycopg[binary]")

選用:建立包含這些項目的 requirements.txt,並使用 python -m pip install -r requirements.txt 進行安裝,以達成可重現的安裝環境。

  1. 將下列程式碼複製到編輯器中,並將其儲存為名為 get_conn.py 的檔案。

    import urllib.parse
    import os
    
    from azure.identity import DefaultAzureCredential
    
    # IMPORTANT! This code is for demonstration purposes only. It's not suitable for use in production.
    # For example, tokens issued by Microsoft Entra ID have a limited lifetime (24 hours by default).
    # In production code, you need to implement a token refresh policy.
    
    def get_connection_uri():
    
        # Read URI parameters from the environment
        dbhost = os.environ['DBHOST']
        dbname = os.environ['DBNAME']
        dbuser = urllib.parse.quote(os.environ['DBUSER'])
        sslmode = os.environ['SSLMODE']
    
        # Use passwordless authentication via DefaultAzureCredential.
        # IMPORTANT! This code is for demonstration purposes only. DefaultAzureCredential() is invoked on every call.
        # In practice, it's better to persist the credential across calls and reuse it so you can take advantage of token
        # caching and minimize round trips to the identity provider. To learn more, see:
        # https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/TOKEN_CACHING.md
        credential = DefaultAzureCredential()
    
        # Call get_token() to get a token from Microsft Entra ID and add it as the password in the URI.
        # Note the requested scope parameter in the call to get_token, "https://ossrdbms-aad.database.windows.net/.default".
        password = credential.get_token("https://ossrdbms-aad.database.windows.net/.default").token
    
        db_uri = f"postgresql://{dbuser}:{password}@{dbhost}/{dbname}?sslmode={sslmode}"
        return db_uri
    
  2. 取得資料庫連線資訊。

    1. Azure 入口網站中,搜尋並選取您的適用於 PostgreSQL 的 Azure 資料庫彈性伺服器執行個體名稱。
    2. 在伺服器的概觀頁面上,複製完整格式的伺服器名稱。 完整格式的伺服器名稱格式一律為 <my-server-name>.postgres.database.azure.com
    3. 在左側功能表的安全性下方,選取驗證。 確保您的帳戶已列在 Microsoft Entra 管理員下方。 若尚未列出,請完成在伺服器上設定 Microsoft Entra 整合 (僅限無密碼)中的步驟。
  3. 為連線 URI 元素設定環境變數:

    set DBHOST=<server-name>
    set DBNAME=<database-name>
    set DBUSER=<username>
    set SSLMODE=require
    
  4. 在您的工作站登入 Azure。 您可以使用 Azure CLI、Azure PowerShell 或 Azure Developer CLI 進行登入。

    驗證程式碼會使用 DefaultAzureCredential 向 Microsoft Entra ID 進行驗證,並取得授權您在伺服器執行個體上執行作業的權杖。 DefaultAzureCredential 支援一連串的驗證認證類型。 在支援的認證中,包含您用來登入開發人員工具 (例如 Azure CLI、Azure PowerShell 或 Azure Developer CLI) 的認證。


如何執行 Python 範例

針對本文中的每個程式碼範例:

  1. 在文字編輯器中建立新檔案。

  2. 將程式碼範例新增至檔案中。

  3. 將檔案以 .py 副檔名儲存至您的專案資料夾中,例如 postgres-insert.py。 若使用 Windows,儲存檔案時請確保選取 UTF-8 編碼。

  4. 在您的專案資料夾中,輸入 python 後面接檔名,例如 python postgres-insert.py

建立資料表並插入資料

下列程式碼範例會使用 psycopg.connect 函式連線至您的適用於 PostgreSQL 的 Azure 資料庫彈性伺服器資料庫,並透過 SQL INSERT 陳述式載入資料。 cursor.execute 函式會針對資料庫執行 SQL 查詢。

import psycopg
from get_conn import get_connection_uri

conn_string = get_connection_uri()

conn = psycopg.connect(conn_string)
print("Connection established")
cursor = conn.cursor()

# Drop previous table of same name if one exists
cursor.execute("DROP TABLE IF EXISTS inventory;")
print("Finished dropping table (if existed)")

# Create a table
cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
print("Finished creating table")

# Insert some data into the table
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150))
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("orange", 154))
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("apple", 100))
print("Inserted 3 rows of data")

# Clean up
conn.commit()
cursor.close()
conn.close()

程式碼會在成功執行後產生下列輸出:

Connection established
Finished dropping table (if existed)
Finished creating table
Inserted 3 rows of data

讀取資料

下列程式碼範例會連線至您的適用於 PostgreSQL 的 Azure 資料庫彈性伺服器資料庫,並使用 cursor.execute 搭配 SQL SELECT 陳述式來讀取資料。 此函式接受查詢,並傳回可使用 cursor.fetchall() 進行反覆運算的結果集。

import psycopg
from get_conn import get_connection_uri

conn_string = get_connection_uri()

conn = psycopg.connect(conn_string)
print("Connection established")
cursor = conn.cursor()

# Fetch all rows from table
cursor.execute("SELECT * FROM inventory;")
rows = cursor.fetchall()

# Print all rows
for row in rows:
    print("Data row = (%s, %s, %s)" %(str(row[0]), str(row[1]), str(row[2])))

# Cleanup
conn.commit()
cursor.close()
conn.close()

程式碼會在成功執行後產生下列輸出:

Connection established
Data row = (1, banana, 150)
Data row = (2, orange, 154)
Data row = (3, apple, 100)

更新資料

下列程式碼範例會連線至您的適用於 PostgreSQL 的 Azure 資料庫彈性伺服器資料庫,並使用 cursor.execute 搭配 SQL UPDATE 陳述式來更新資料。

import psycopg
from get_conn import get_connection_uri

conn_string = get_connection_uri()

conn = psycopg.connect(conn_string)
print("Connection established")
cursor = conn.cursor()

# Update a data row in the table
cursor.execute("UPDATE inventory SET quantity = %s WHERE name = %s;", (200, "banana"))
print("Updated 1 row of data")

# Cleanup
conn.commit()
cursor.close()
conn.close()

刪除資料

下列程式碼範例會連線至您的適用於 PostgreSQL 的 Azure 資料庫彈性伺服器資料庫,並使用 cursor.execute 搭配 SQL DELETE 陳述式,以刪除您先前插入的庫存項目。

import psycopg
from get_conn import get_connection_uri

conn_string = get_connection_uri()

conn = psycopg.connect(conn_string)
print("Connection established")
cursor = conn.cursor()

# Delete data row from table
cursor.execute("DELETE FROM inventory WHERE name = %s;", ("orange",))
print("Deleted 1 row of data")

# Cleanup
conn.commit()
cursor.close()
conn.close()