快速入門:使用 Python 連接並查詢 Azure HorizonDB(預覽版)的資料

在這個快速入門中,你透過使用 Python 連接到 Azure HorizonDB 實例。 接著,您將在 macOS、Ubuntu Linux 和 Windows 平台上使用 SQL 陳述式,在資料庫中進行查詢、插入、更新和刪除資料。

本文的步驟包括 PostgreSQL 認證。

PostgreSQL 認證使用儲存在 PostgreSQL 的帳號,而你需要自己管理密碼的輪替。

這篇文章假設你熟悉使用 Python 開發,但你是使用 Azure HorizonDB 的新手。

先決條件

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

準備開發環境

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

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

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

安裝 Python 程式庫

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

安裝 psycopg 模組,以便連線至 PostgreSQL 資料庫並進行查詢。

# Recommended: install the binary wheel that bundles a compatible libpq wrapper (Windows/macOS)
python -m pip install "psycopg[binary]"

# Linux alternative (if you prefer building against system libpq):
sudo apt-get update
sudo apt-get install -y libpq-dev build-essential python3-dev
python -m pip install psycopg

新增驗證程式碼

在此區塊中,您將驗證碼加入工作目錄,並執行與叢集實例進行認證與授權所需的額外步驟。

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

必要套件 (本文範例):

  • 密碼範例: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
    
    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'])
    password = os.environ['DBPASSWORD']
    sslmode = os.environ['SSLMODE']
    db_uri = f"host={dbhost} dbname={dbname} user={dbuser} password={password} sslmode={sslmode}"
       # Construct connection URI
       return db_uri
    
  2. 取得資料庫連線資訊。

    使用 Azure 入口網站:

    1. 在Azure入口網站左側選單中,選擇所有資源,然後搜尋你已建立的叢集。

    2. 選擇叢集名稱。

    3. 在資源功能表中,選取 [概觀]。 將滑鼠移到顯示為 主要端點(讀寫)的值上,然後選擇 「複製到剪貼簿 」按鈕。

      顯示概觀頁面中主要端點值的螢幕擷圖。

    4. 如果您忘記系統管理員登入的密碼,您可以使用 [重設密碼] 按鈕來重設密碼。

      螢幕擷取畫面顯示 [概觀] 頁面中的 [重設密碼] 按鈕。

  3. 為連線 URI 元素設定環境變數:

    set DBHOST=<cluster-name>
    set DBNAME=<database-name>
    set DBUSER=<username>
    set DBPASSWORD=<password>
    set SSLMODE=require
    

如何執行 Python 範例

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

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

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

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

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

建立資料表及插入資料

以下程式碼範例是使用 psycopg.connect 函式連接到你的 Azure HorizonDB 叢集,並以 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

讀取資料

以下程式碼範例連接你的 Azure HorizonDB 叢集,並使用 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)

更新資料

以下程式碼範例連接您的 Azure HorizonDB 叢集,並使用 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()

刪除資料

以下程式碼範例連接你的 Azure HorizonDB 叢集,並使用 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()