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

标签 python postgresql psycopg2 postgresql-copy

我在 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/

相关文章:

postgresql - 我在本地计算机上收到 “docker: invalid reference format.”

python - InternalError : current transaction is aborted, 命令被忽略,直到事务 block 结束

python - psycopg2 映射 Python : "list of dicts" to Postgres : "array of composite type" for an INSERT statement

python - 我收到错误 "ValueError: endog is required to have ndim 1 but has ndim 2"

python - 获取两个二维列表之间的差异

python - Django 在没有 Q 的情况下组合两个查询

mysql - postgres和mysql数据库服务器同步?

python - 如何安装 psycopg2 以在 HDInsight PySpark Jupyter 笔记本中使用

Python列表弹出

java - 在 IMAP 帐户中,如何创建仅包含交换附件的邮件的精确副本?