快速入门:使用 Python 连接到 Azure Database for PostgreSQL 并查询其中的数据 - 单一服务器

适用于:Azure Database for PostgreSQL 单一服务器

重要

Azure Database for PostgreSQL - 单一服务器即将停用。 强烈建议升级到 Azure Database for PostgreSQL - 灵活服务器。 有关迁移到 Azure Database for PostgreSQL 灵活服务器的详细信息,请参阅 Azure Database for PostgreSQL 单一服务器的最新动态?

在快速入门中,了解如何连接到 Azure Database for PostgreSQL 单一服务器上的数据库,以及如何运行 SQL 语句以在 macOS、Ubuntu Linux 或 Windows 上使用 Python 进行查询。

提示

如果希望使用 PostgreSQL 生成 Django 应用程序,请查看教程 - 使用 PostgreSQL 部署 Django Web 应用教程。

先决条件

对于本快速入门,你需要:

  • 具有活动订阅的 Azure 帐户。 创建试用帐户

  • 使用 Azure 门户
    Azure CLI 创建 Azure Database for PostgreSQL 单一服务器(如果没有)。

  • 请完成以下操作之一以启用连接,具体取决于你使用的是公共访问还是私有访问。

    操作 连接方法 操作指南
    配置防火墙规则 公用 Portal
    CLI
    配置服务终结点 公用 Portal
    CLI
    配置专用链接 Private Portal
    CLI
  • Python 2.7 或 3.6+。

  • 最新 pip 包安装程序。

  • 在终端或命令提示符窗口中使用 pip install psycopg2-binary 安装 psycopg2。 有关详细信息,请参阅如何安装 psycopg2

获取数据库连接信息

连接到 Azure Database for PostgreSQL 数据库需要完全限定的服务器名称和登录凭据。 可以从 Azure 门户获取此信息。

  1. Azure 门户中,搜索 Azure Database for PostgreSQL 服务器名称并选择该名称。

  2. 在服务器的“概述”页上,复制完全限定的“服务器名称”和“管理员用户名” 。 完全限定的“服务器名称”始终采用“<我的服务器名称>.postgres.database.chinacloudapi.cn”的格式,“管理员用户名”始终采用“<我的管理员用户名>@<我的服务器名称>”的格式。

    你还需要管理员密码。 如果忘记,可以从此页重置它。

    Azure Database for PostgreSQL server name

重要

请替换以下值:

  • <server-name><admin-username> 替换为从 Azure 门户复制的值。
  • <admin-password> 替换为服务器密码。
  • <database-name> 替换为你在创建服务器时自动创建一个名为 postgres 的默认数据库。 你可以重命名该数据库,或使用 SQL 命令创建新的数据库

步骤 1:连接并插入数据

下面的代码示例使用

  • psycopg2.connect 函数连接到 Azure Database for PostgreSQL 数据库,并使用 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

步骤 2:读取数据

下面的代码示例连接到 Azure Database for PostgreSQL 数据库,并使用


# 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])))

步骤 3:更新数据

下面的代码示例使用 cursor.execute 和 SQL UPDATE 语句来更新数据。


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

步骤 5:删除数据

下面的代码示例运行 cursor.execute 和 SQL DELETE 语句删除先前插入的清单项。


# Delete data row from table

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

清理资源

若要清理本快速入门中使用的所有资源,请使用以下命令删除该资源组:

az group delete \
    --name $AZ_RESOURCE_GROUP \
    --yes

后续步骤