使用 python 和 psycopg2 将 CSV 导入 postgres 时出错

use*_*919 4 python csv postgresql psycopg2

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

\n\n
 Traceback (most recent call last):\n File "<stdin>", line 1, in <module>\n psycopg2.ProgrammingError: must be superuser to COPY to or from a file\nHINT:  Anyone can COPY to stdout or from stdin. psql\'s \\copy command also works for anyone.\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

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

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

\n\n

编辑

\n\n

查看@Ilja Everil\xc3\xa4 提供的链接后,我尝试了以下操作:

\n\n
cur.copy_from(\'/tmp/tmpJopiUG/downloaded_xls.csv\', \'test_copy\')\n
Run Code Online (Sandbox Code Playgroud)\n\n

我收到错误:

\n\n
Traceback (most recent call last):\nFile "<stdin>", line 1, in <module>\nTypeError: argument 1 must have both .read() and .readline() methods\n
Run Code Online (Sandbox Code Playgroud)\n\n

我如何给出这些方法?

\n

Ilj*_*ilä 6

尝试使用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()
Run Code Online (Sandbox Code Playgroud)

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

  • 请记住[`commit()`](http://initd.org/psycopg/docs/connection.html#connection.commit)。 (2认同)