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

标签 python postgresql etl psycopg2

我正在尝试使用 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/

相关文章:

python - 煎饼排序中最短翻转序列的计数

postgresql - 在 hsqldb 上运行触发的 postgresql 函数

postgresql - 带有 postgres 的 SQLalchemy。尝试获取 'DISTINCT ON' 而不是 'DISTINCT'

sql-server - SSIS ForEach 循环 - 更改 for 循环内的连接

python - 如何更改字段的顺序?

python - 为什么 wxGlade 强制将 sizer 作为 wx.Frame 的第一个子元素?

java - JPA 2 (EclipseLink) 尝试使用 UUID 作为主键 EntityManager.find() 总是抛出异常(数据库是 PostgreSQL)

apache - 使用 NiFi 更新 CSV 内字段中的值

sql-server - 根据字段值在ssis中拆分行

python - 安装 cx_Freeze