python - Psycopg copy_expert 方法 - 如何正确使用

标签 python postgresql psycopg2 psycopg

我正在尝试运行这样的代码:

query = "copy  (select email from my_table) TO 'STDOUT' WITH (FORMAT csv, DELIMITER '|', QUOTE '^', HEADER FALSE)"
out_file = StringIO()
cursor.copy_expert(query, out_file, size=8192)

使用 copy_expert cursor method .

但是我收到了这个错误:

Traceback (most recent call last):
  File "etl/scripts/scratch.py", line 32, in <module>
    cursor.copy_expert(query, out_file, size=8192)
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.

我无法以 super 用户身份运行它,而且似乎不需要这样做,因为我没有接触任何真实文件。

最佳答案

two variants of COPY TO :

  • COPY TO STDOUT,将数据流式传输回客户端,以及
  • COPY TO 'filename',写入服务器端文件(需要 super 用户权限)。

您的 COPY 语句在 STDOUT 关键字周围加了引号,导致它被解释为文件名。只需删除它们即可。

关于python - Psycopg copy_expert 方法 - 如何正确使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41616578/

相关文章:

DLL 中的 Python (c++) Visual Studio

python - Python 上的 SQL 语法不正确

postgresql - 如何从 CTE 字段别名中定义的字段集中获取字段?

postgresql - Postgres : insert value from another table as part of multi-row insert?

python - 将 Unnest 与 psycopg2 一起使用

django - 为什么我的数据库不会使用 django_extensions、postgres 和 psycopg2 重置?

Python GTK3 工具栏加速器不起作用

python - 您如何知道哪个 pyTZ 实际上会按预期执行?

postgresql - pg_restore 加载转储失败