gpt4 book ai didi

python - 使用python将数据从csv复制到postgresql

转载 作者:太空狗 更新时间:2023-10-29 17:26:11 26 4
gpt4 key购买 nike

我在 Windows 7 64 位上。我有一个 csv 文件“data.csv”。我想通过 python 脚本将数据导入 postgresql 表“temp_unicommerce_status”。

我的脚本是:

import psycopg2
conn = psycopg2.connect("host='localhost' port='5432' dbname='Ekodev' user='bn_openerp' password='fa05844d'")
cur = conn.cursor()
cur.execute("""truncate table "meta".temp_unicommerce_status;""")
cur.execute("""Copy temp_unicommerce_status from 'C:\Users\n\Desktop\data.csv';""")
conn.commit()
conn.close()

我收到这个错误

Traceback (most recent call last):
File "C:\Users\n\Documents\NetBeansProjects\Unicommerce_Status_Update\src\unicommerce_status_update.py", line 5, in <module>
cur.execute("""Copy temp_unicommerce_status from 'C:\\Users\\n\\Desktop\\data.csv';""")
psycopg2.ProgrammingError: must be superuser to COPY to or from a file
HINT: Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.

最佳答案

使用 copy_from cursor method

f = open(r'C:\Users\n\Desktop\data.csv', 'r')
cur.copy_from(f, temp_unicommerce_status, sep=',')
f.close()

文件必须作为对象传递。

由于您是从 csv 文件处理的,因此有必要指定分隔符,因为默认为制表符

关于python - 使用python将数据从csv复制到postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30050097/

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