【问题标题】:Error when importing CSV to postgres with python and psycopg2使用 python 和 psycopg2 将 CSV 导入到 postgres 时出错
【发布时间】:2016-10-06 01:20:06
【问题描述】:

我尝试使用 python 和 psycopg2 将 CSV 文件从文件夹复制到 postgres 表,但出现以下错误:

 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 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.

我也尝试通过python环境运行它:

  constr = "dbname='db_name' user='user' host='localhost' password='pass'"
  conn = psycopg2.connect(constr)
  cur = conn.cursor()
  sqlstr = "COPY test_2 FROM '/tmp/tmpJopiUG/downloaded_xls.csv' DELIMITER ',' CSV;"
  cur.execute(sqlstr)

我仍然收到上述错误。我尝试了 \copy 命令,但这仅适用于 psql。为了能够通过我的 python 脚本执行此操作,有什么替代方法?

已编辑

查看@Ilja Everilä 提供的链接后,我尝试了这个:

cur.copy_from('/tmp/tmpJopiUG/downloaded_xls.csv', 'test_copy')

我得到一个错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument 1 must have both .read() and .readline() methods

我如何给出这些方法?

【问题讨论】:

标签: python postgresql csv psycopg2


【解决方案1】:

您也可以使用 copy_from。请看下面的代码

with open('/tmp/tmpJopiUG/downloaded_xls.csv') as f:
 cur.copy_from(f, table_name,sep=',')
conn.commit()

【讨论】:

    【解决方案2】:

    尝试使用cursor.copy_expert()

    constr = "dbname='db_name' user='user' host='localhost' password='pass'"
    conn = psycopg2.connect(constr)
    cur = conn.cursor()
    sqlstr = "COPY test_2 FROM STDIN DELIMITER ',' CSV"
    with open('/tmp/tmpJopiUG/downloaded_xls.csv') as f:
        cur.copy_expert(sqlstr, f)
    conn.commit()
    

    您必须在 python 中打开文件 并将其传递给 psycopg,然后将其转发到 postgres 的标准输入。由于您将 CSV 参数用于 COPY,因此您必须使用您自己传递 COPY 语句的专家版本。

    【讨论】:

    • 哦。那肯定不会发生。我希望你注意到我的编辑,我将调用固定在execute()copy_expert() 之间(那里有一点复制和粘贴错误)。但是,它确实不应该出现段错误。
    • 是的。编辑后,我没有收到分段错误错误。但实际上什么也没发生。没有错误或警告,但 csv 仍未上传。
    • 记得commit()
    • 天哪!非常感谢!提交成功了!我总是忘记我需要提交更改。
    • 我强烈推荐using with-statements with connection objects for transaction handling,以后你要少写很多样板。
    猜你喜欢
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多