gpt4 book ai didi

python - psycopg2.ProgrammingError : syntax error at or near "\"

转载 作者:太空狗 更新时间:2023-10-30 01:02:16 31 4
gpt4 key购买 nike

我有一个 python 模块,可以将数据从表复制到文件。我使用 postgresql 作为数据库服务器。 COPY 是用于执行上述操作的命令。

但是在博客 (http://grokbase.com/t/postgresql/pgsql-general/058tagtped/about-error-must-be-superuser-to-copy-to-or-from-a-file) 中指出,您可以在客户端的“psql”中使用\copy,但出于安全原因,您必须是 super 用户才能在服务器端执行 COPY。所以我使用了\copy 命令。当我尝试执行以下方法时,它会导致错误

psycopg2.ProgrammingError: syntax error at or near "\" LINE 1: \copy

我找不到它抛出错误的原因。有人可以帮帮我吗?

def process():
query="\copy %s TO %s"%('test_table', 'test_file.txt')

@env.with_transaction()
def do_execute(db):
cursor = db.cursor()
cursor.execute(query)

do_execute is a database wrapper, which creates connection and executes the query.

最佳答案

\ 是 Python 字符串中的转义符,因此您的字符串包含转义符 \c。但是 \c 在 Python 中是无效转义,Python 保留无效转义不变,所以 "\copy" 就是 \copy。 (因此@tiziano 的回答具有误导性)。

>>> print "\c"
\c

真正的问题是 \copy 是一个 psql 命令,而不是服务器端的 PostgreSQL 命令。除了 psql 之外,您不能将它与客户端一起使用。您必须改为使用 the psycopg2 support for COPY通过您的客户端驱动程序来完成。

关于python - psycopg2.ProgrammingError : syntax error at or near "\",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18123212/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com