PostgreSQL Python 教程: 将数据插入表中

八月 13, 2023

摘要:本教程逐步向您展示如何使用 Python 将一行或多行插入到 PostgreSQL 表中。

将一行插入 PostgreSQL 表的步骤

在 Python 中要将行插入到 PostgreSQL 表中,请使用以下步骤:

首先,通过调用psycopg模块的connect()函数连接到 PostgreSQL 数据库服务器

conn = psycopg2.connect(dsn)

connect()函数返回一个connection类的新实例。

接下来,通过调用该connection对象的cursor()方法来创建一个新的cursor对象。

cur = conn.cursor()

然后,通过使用输入值调用cursor对象的execute()方法,执行INSERT语句。

cur.execute(sql, (value1,value2))

您将该INSERT语句作为第一个参数传递给execute()方法,并将值列表作为第二个参数传递给该方法。

如果表的主键序列标识列,则可以在插入行后获取生成的 ID。

为此,您可以使用INSERT语句中的RETURNING id子句。调用execute()方法后,调用cursor对象的fetchone()方法来获取id值,如下所示:

id = cur.fetchone()[0]

之后,调用该connection对象的commit()方法将更改永久保存到数据库中。

conn.commit()

如果忘记调用该commit()方法,psycopg2将不会对表进行任何更改。

最后,通过调用cursorconnection对象的close()方法,关闭与 PostgreSQL 数据库服务器的连接。

cur.close()
conn.close()

将一行插入 PostgreSQL 表的示例

为了演示,我们将使用我们在创建表教程中创建的suppliers数据库中的vendors表。

vendors_table

以下insert_vendor()函数将新行插入vendors表中并返回新生成的vendor_id值。

#!/usr/bin/python

import psycopg2
from config import config

def insert_vendor(vendor_name):
    """ insert a new vendor into the vendors table """
    sql = """INSERT INTO vendors(vendor_name)
             VALUES(%s) RETURNING vendor_id;"""
    conn = None
    vendor_id = None
    try:
        # read database configuration
        params = config()
        # connect to the PostgreSQL database
        conn = psycopg2.connect(**params)
        # create a new cursor
        cur = conn.cursor()
        # execute the INSERT statement
        cur.execute(sql, (vendor_name,))
        # get the generated id back
        vendor_id = cur.fetchone()[0]
        # commit the changes to the database
        conn.commit()
        # close communication with the database
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()

    return vendor_id

将多行插入 PostgreSQL 表的示例

向表中插入多行的步骤与插入一行的步骤类似,只不过在第三步中,您调用的是cursor对象的executemany()方法,而不是调用execute()方法。

例如,以下insert_vendor_list()函数将多行插入vendors表中。

def insert_vendor_list(vendor_list):
    """ insert multiple vendors into the vendors table  """
    sql = "INSERT INTO vendors(vendor_name) VALUES(%s)"
    conn = None
    try:
        # read database configuration
        params = config()
        # connect to the PostgreSQL database
        conn = psycopg2.connect(**params)
        # create a new cursor
        cur = conn.cursor()
        # execute the INSERT statement
        cur.executemany(sql,vendor_list)
        # commit the changes to the database
        conn.commit()
        # close communication with the database
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()

要测试insert_vendor()insert_vendor_list()函数,您可以使用以下代码片段:

if __name__ == '__main__':
    # insert one vendor
    insert_vendor("3M Co.")
    # insert multiple vendors
    insert_vendor_list([
        ('AKM Semiconductor Inc.',),
        ('Asahi Glass Co Ltd.',),
        ('Daikin Industries Ltd.',),
        ('Dynacast International Inc.',),
        ('Foster Electric Co. Ltd.',),
        ('Murata Manufacturing Co. Ltd.',)
    ])

在本教程中,您学习了从 Python 程序向 PostgreSQL 表插入一行或多行的步骤。