gpt4 book ai didi

python - 在源和目标上使用具有不同列数的 Python copy_from

转载 作者:行者123 更新时间:2023-12-04 01:49:01 24 4
gpt4 key购买 nike

我正在尝试使用 Python 从 CSV 源到 PostgreSQL 数据库的新 ETL 过程。

我已经为目的地做了表。但是,我的数据库表中有 create_at 列,默认值是 CURRENT_DATE。另一方面,我在 CSV 文件中没有 create_at 列。

数据库中的 WP_SALES 表包括:

id (int) PK
order_date (timestamp)
order_status (character varying)
customer_id (smallint)
product (character varying)
product_category (character varying)
quantity (smallint)
total_price (money)
create_at (date) DEFAULT CURRENT_DATE

在 CSV 上,它包括:
id 
order_date
order_status
customer_id
product
product_category
quantity
total_price

这是我试过的代码:
import psycopg2
conn = psycopg2.connect ("host=localhost dbname=postgres user=postgres port=5432")
cur = conn.cursor()
with open('[Technical Test - Data Engineer] Sale Report - wp.csv', 'r') as source:
next(source)
cur.copy_from(source, 'public."WP_SALES"', sep=',')

conn.commit()

我希望输出将是加载到表中的 CSV 上的所有数据,其中 created_at 列填充了其默认值 (CURRENT_DATE)。

我得到的是这个错误:
Traceback (most recent call last):
File "D:\Warung Pintar\TESTQuery", line 8, in <module>
cur.copy_from(source, 'public."WP_SALES"', sep=',')
psycopg2.DataError: missing data for column "create_at"
CONTEXT: COPY WP_SALES, line 1: "127530,2018-10-20T03:41:14,sale,1645,ABC001,Minuman Sachet,2,19400"

[Finished in 0.2s]

我希望在不调整 CSV 文件的情况下解决问题。

提前致谢。

最佳答案

如 psycopg2 documentation 中所述copy_from() 具有列的命名参数

columns – iterable with name of the columns to import. The length and types should match the content of the file to read. If not specified, it is assumed that the entire table matches the file structure.



所以以下应该是你需要的
cur.copy_from(source, 'public."WP_SALES"', sep=',', columns=['id', 'order_date', 'order_status', 'customer_id', 'product', 'product_category', 'quantity', 'total_price'])

关于python - 在源和目标上使用具有不同列数的 Python copy_from,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54150454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com