python - 将 Unnest 与 psycopg2 一起使用

标签 python postgresql psycopg2

我构建了一个 Web UI 作为 ETL 应用程序,允许用户选择一些包含大量记录的 CSV 和 TSV 文件,我正在尝试将它们插入 PostgreSQL 数据库。正如已经很好地评论过的那样,这个过程有点慢。经过一些研究,看起来使用 UNNEST 函数将是我的答案,但我在实现它时遇到了麻烦。老实说,在研究 Python 中的任何数据处理时,我只是没有找到一个很好的演练教程,就像我通常做的那样。

这是我存储它们时的 SQL 字符串(稍后在函数中使用):

salesorder_write = """
  INSERT INTO api.salesorder (
    site,
    sale_type,
    sales_rep,
    customer_number,
    shipto_number,
    cust_po_number,
    fob,
    order_number
  ) VALUES (
    UNNEST(ARRAY %s)

"""

我将这个字符串与元组列表一起使用,如下所示:

for order in orders:
        inputs=(
            order['site'],
            order['sale_type'],
            order['sales_rep'],
            order['customer_number'],
            order['shipto_number'],
            order['cust_po_number'],
            order['fob'],
            order['order_number']
        )
        tup_list.append(inputs)
cur.execute(strSQL,tup_list)

这给我的错误是在字符串格式化期间并非所有参数都已转换。我的第一个问题是我需要如何构建我的 SQL 才能传递我的元组列表。我的第二个问题是,我能否以大致相同的方式使用现有的字典结构?

最佳答案

unnest 并不优于现在(自 Psycopg 2.7 起)规范 execute_values :

from psycopg2.extras import execute_values
orders = [
    dict (
        site = 'x',
        sale_type = 'y',
        sales_rep = 'z',
        customer_number = 1,
        shipto_number = 2,
        cust_po_number = 3,
        fob = 4,
        order_number = 5
    )
]
salesorder_write = """
    insert into t (
        site,
        sale_type,
        sales_rep,
        customer_number,
        shipto_number,
        cust_po_number,
        fob,
        order_number
    ) values %s
"""
execute_values (
    cursor,
    salesorder_write,
    orders,
    template = """(
        %(site)s,
        %(sale_type)s,
        %(sales_rep)s,
        %(customer_number)s,
        %(shipto_number)s,
        %(cust_po_number)s,
        %(fob)s,
        %(order_number)s
    )""",
    page_size = 1000
)

关于python - 将 Unnest 与 psycopg2 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46373804/

相关文章:

python - 修改 Pandas 数据框中的许多列

python - 将函数应用于数据框列的最有效方法

postgresql - 如何将 Spark DataFrame 写入 Postgres DB

sql - Postgresql 查询两个具有相同命名表的不同数据库

python - 如何教 SQLAlchemy 从断开连接中恢复?

python - 如何仅从对象边界获取对象质心?

python - 读写模式python

node.js - 顺序递增跳数

python - psycopg2.sql 发生了什么?

python - cur.executemany 在字符串格式化期间并非所有参数都已转换