PostgreSQL Python 教程: 创建表

八月 13, 2023

摘要:在本教程中,您将学习如何使用 Python 在 PostgreSQL 数据库中创建新表。

本教程假设您知道如何编写 CREATE TABLE 语句。如果还不知道怎么编写,您应该查看 CREATE TABLE 教程

在 Python 中创建 PostgreSQL 表的步骤

要在 PostgreSQL 数据库中创建新表,请使用以下步骤:

  1. 首先,构造CREATE TABLE语句。
  2. 接下来,通过调用connect()函数连接到 PostgreSQL 数据库。该connect()函数会返回一个connection对象。
  3. 然后,通过调用connection对象的cursor()方法来创建一个cursor对象。
  4. 之后,通过调用cursor对象的execute()方法来执行CREATE TABLE语句。
  5. 最后,通过调用cursorconnection对象close()的方法,关闭与 PostgreSQL 数据库服务器的通信。

在 Python 中创建表的示例

1) 创建 Python 程序

首先,创建一个名为create_table.py的新文件。

其次,在create_table.py文件内定义一个名为create_tables()的新函数。

create_tables()函数在suppliers数据库中创建四个表:vendorspartsvendor_partspart_drawings

PostgreSQL Python Sample Database Diagram

#!/usr/bin/python

import psycopg2
from config import config

def create_tables():
    """ create tables in the PostgreSQL database"""
    commands = (
        """
        CREATE TABLE vendors (
            vendor_id SERIAL PRIMARY KEY,
            vendor_name VARCHAR(255) NOT NULL
        )
        """,
        """ CREATE TABLE parts (
                part_id SERIAL PRIMARY KEY,
                part_name VARCHAR(255) NOT NULL
                )
        """,
        """
        CREATE TABLE part_drawings (
                part_id INTEGER PRIMARY KEY,
                file_extension VARCHAR(5) NOT NULL,
                drawing_data BYTEA NOT NULL,
                FOREIGN KEY (part_id)
                REFERENCES parts (part_id)
                ON UPDATE CASCADE ON DELETE CASCADE
        )
        """,
        """
        CREATE TABLE vendor_parts (
                vendor_id INTEGER NOT NULL,
                part_id INTEGER NOT NULL,
                PRIMARY KEY (vendor_id , part_id),
                FOREIGN KEY (vendor_id)
                    REFERENCES vendors (vendor_id)
                    ON UPDATE CASCADE ON DELETE CASCADE,
                FOREIGN KEY (part_id)
                    REFERENCES parts (part_id)
                    ON UPDATE CASCADE ON DELETE CASCADE
        )
        """)
    conn = None
    try:
        # read the connection parameters
        params = config()
        # connect to the PostgreSQL server
        conn = psycopg2.connect(**params)
        cur = conn.cursor()
        # create table one by one
        for command in commands:
            cur.execute(command)
        # close communication with the PostgreSQL database server
        cur.close()
        # commit the changes
        conn.commit()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()

if __name__ == '__main__':
    create_tables()

2) 执行 Python 程序

要执行 Python 程序,请使用以下命令:

python create_table.py

3) 验证表创建

首先,使用 psql 程序登录 PostgreSQL 数据库服务器。

其次,使用\dt 命令显示suppliers数据库中的表列表。

suppliers=# \dt
             List of relations
 Schema |     Name      | Type  |  Owner
--------+---------------+-------+----------
 public | part_drawings | table | postgres
 public | parts         | table | postgres
 public | vendor_parts  | table | postgres
 public | vendors       | table | postgres
(4 rows)

从输出中可以清楚地看到,我们在suppliers数据库中成功创建了四个表。

如果您使用其他客户端工具(例如 pgAdmin),您可以通过public模式下的表列表查看表。

在本教程中,您逐步学习了如何使用 psycopg 数据库适配器在 Python 中创建新的 PostgreSQL 表。