Psycopg copy_expert方法 - 如何正确使用

时间:2017-01-12 15:10:45

标签: 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.

我无法以超级用户身份运行它,因为我没有触及任何真实文件,所以似乎不应该这样做。

2 个答案:

答案 0 :(得分:5)

two variants of COPY TO

  • COPY TO STDOUT,将数据流回客户端,
  • COPY TO 'filename',写入服务器端文件(需要超级用户权限)。

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

答案 1 :(得分:0)

您也可以使用 csv 模块代替 copy_expert

import csv

from sqlalchemy.orm import Session
from sqlalchemy import create_engine

_url = f"snowflake://user:test124/snow.com:443/DB/WAREHOUSE/ACCOUNT"
with open("sample.csv", "w") as csv_file:
    with Session(create_engine(_url).engine) as session:
        result = session.execute("select * from my_table")
        data = result.fetchall()
        csv_writer = csv.writer(csv_file)
        csv_writer.writerows(data)