gpt4 book ai didi

postgresql - Postgres 9.4 : COPY with transformation step?

转载 作者:行者123 更新时间:2023-11-29 12:11:42 24 4
gpt4 key购买 nike

我有一些非常大的 CSV 文件,我正在使用 Postgres 9.4。我正在使用 Postgres's COPY command有效地将它们导入我的数据库。这很好用:

    cursor = conn.cursor()
copy_str = "COPY mytable(presentation_code,quantity,"
copy_str += "processing_date,price_per_unit) FROM STDIN "
copy_str += "WITH DELIMITER AS ','"
file_obj = open(filename)
cursor.copy_expert(copy_str, file_obj)
try:
conn.commit()
except Exception as err:
print 'EXCEPTION:', err

问题是我必须在数据文件适合于 COPY 之前对它们运行一些转换步骤。其中包括重新排序字段、将字符串转换为 float 、转换日期以便它们适用于 Postgres,以及计算一些值(尽管我可能会跳过这最后一步):

for row in reader:
presentation_code = row[0].strip()
quantity = int(row[1])
period = row[9]
processing_date = period[:4] + '-' + period[4:] + '-01'
if row[4]:
price_per_unit = actual_cost / float(row[4])
else:
price_per_unit = 0
output = [presentation_code, quantity, processing_date, price_per_unit]
writer.writerow(output)

是否有任何 Postgres 工具可以让我在一个命令中完成这两个步骤(转换,然后复制)?或者这只是一个必要的步骤?

最佳答案

您必须将转换编写为一个程序,该程序将每一行从其标准输入获取到标准输出,然后将其用作 copy 命令本身的过滤器。详见copy手册页(看“程序”部分):http://www.postgresql.org/docs/9.4/static/sql-copy.html .请注意,该程序将作为“postgres”用户运行(如果您想从客户端应用程序运行它,您可以使用 psql 的\copy 命令,http://www.postgresql.org/docs/9.4/static/app-psql.html)。

关于postgresql - Postgres 9.4 : COPY with transformation step?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31003896/

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