快速入門:使用 Python 連線和查詢 適用於 PostgreSQL 的 Azure 資料庫 - 彈性伺服器中的數據

適用於:適用於 PostgreSQL 的 Azure 資料庫 - 彈性伺服器

在本快速入門中,您會使用 Python 連線到 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器實例。 然後,您可以使用 SQL 語句,從 Mac、Ubuntu Linux 和 Windows 平台查詢、插入、更新和刪除資料庫中的數據。

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

必要條件

  • 具有有效訂用帳戶的 Azure 帳戶。 免費建立帳戶
  • 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器實例。 若要建立 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器實例,請參閱使用 Azure 入口網站 建立 適用於 PostgreSQL 的 Azure 資料庫 - 彈性伺服器實例。
  • Python 2.7 或 3.6+。
  • 最新的 pip 套件安裝程式。

準備用戶端工作站

  • 如果您建立 適用於 PostgreSQL 的 Azure 資料庫 具有私人存取權(VNet 整合)的彈性伺服器實例,您必須從與伺服器相同 VNet 內的資源連線到您的伺服器。 您可以建立虛擬機,並將其新增至使用 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器實例建立的 VNet。 請參閱使用 Azure CLI 建立和管理 適用於 PostgreSQL 的 Azure 資料庫 - 彈性伺服器虛擬網路。
  • 如果您使用公用存取權建立 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器實例(允許的IP 位址),您可以將本機IP位址新增至您伺服器上的防火牆規則清單。 請參閱使用 Azure CLI 建立和管理 適用於 PostgreSQL 的 Azure 資料庫 - 彈性伺服器防火牆規則。

安裝適用於PostgreSQL的 Python 連結庫

psycopg2 模組可讓您連線及查詢 PostgreSQL 資料庫,並可作為 Linux、macOS 或 Windows 滾輪套件使用。 安裝模組的二進位版本,包括所有相依性。

若要安裝 psycopg2,請開啟終端機或命令提示字元,然後執行 命令 pip install psycopg2

取得資料庫連線資訊

連線 至 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器實例需要完整的伺服器名稱和登入認證。 您可以從 Azure 入口網站 取得此資訊。

  1. Azure 入口網站 中,搜尋並選取您的 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器名稱。

  2. 在伺服器的 [概觀] 頁面上,複製完整伺服器名稱和管理員 用戶名稱。 完整伺服器名稱的格式一律<為 my-server-name.postgres.database.azure.com。>

    您也需要系統管理員密碼。 如果您忘記了,您可以從 [概觀] 頁面重設它。

如何執行 Python 範例

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

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

  2. 將程式代碼範例新增至 檔案。 在程式代碼中,取代:

    • <server-name><admin-username> ,其中包含您從 Azure 入口網站 複製的值。
    • <admin-password> 使用您的伺服器密碼。
    • <database-name>具有 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器資料庫的名稱。 當您建立伺服器時,會自動建立名為 postgres 的預設資料庫。 您可以使用 SQL 命令重新命名該資料庫或建立新的資料庫。
  3. 將檔案儲存在擴展名為 .py 的項目資料夾中,例如 postgres-insert.py。 針對 Windows,請確定儲存盤案時已選取 UTF-8 編碼。

  4. 若要執行檔案,請變更為命令列介面中的項目資料夾,然後輸入 python 後面接著檔名,例如 python postgres-insert.py

建立數據表並插入數據

下列程式代碼範例會使用 psycopg2.connect 函式連線到 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器資料庫,並使用 SQL INSERT 語句載入數據。 cursor.execute 函式會針對資料庫執行 SQL 查詢。

import psycopg2

# Update connection string information 
host = "<server-name>"
dbname = "<database-name>"
user = "<admin-username>"
password = "<admin-password>"
sslmode = "require"

# Construct connection string
conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password, sslmode)
conn = psycopg2.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()

成功執行程式代碼時,會產生下列輸出:

Command-line output

讀取數據

下列程式代碼範例會連線到 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器資料庫,並使用 cursor.execute 搭配 SQL SELECT 語句來讀取數據。 此函式會接受查詢並傳回結果集,以使用 cursor.fetchall() 逐一查看

import psycopg2

# Update connection string information
host = "<server-name>"
dbname = "<database-name>"
user = "<admin-username>"
password = "<admin-password>"
sslmode = "require"

# Construct connection string
conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password, sslmode)
conn = psycopg2.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()

更新資料

下列程式代碼範例會連線到 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器資料庫,並使用 cursor.execute 搭配 SQL UPDATE 語句來更新數據。

import psycopg2

# Update connection string information
host = "<server-name>"
dbname = "<database-name>"
user = "<admin-username>"
password = "<admin-password>"
sslmode = "require"

# Construct connection string
conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password, sslmode)
conn = psycopg2.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 psycopg2

# Update connection string information
host = "<server-name>"
dbname = "<database-name>"
user = "<admin-username>"
password = "<admin-password>"
sslmode = "require"

# Construct connection string
conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password, sslmode)
conn = psycopg2.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()

下一步