psycopg2.ProgrammingError:“\"处或附近的语法错误;

编程入门 行业动态 更新时间:2024-10-23 00:30:30
本文介绍了psycopg2.ProgrammingError:“\"处或附近的语法错误;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

psycopg2.ProgrammingError:\"第 1 行或附近的语法错误:\copy

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

def process():query="\copy %s TO %s"%('test_table', 'test_file.txt')@env.with_transaction()def do_execute(db):游标 = db.cursor()游标.执行(查询)

do_execute 是一个数据库包装器,它创建连接和执行查询.

解决方案

\ 是 Python 字符串中的转义符,因此您的字符串包含转义符 \c.然而 \c 在 Python 中是一个无效的转义,并且 Python 保持无效的转义不变,所以 "\copy" 只是 \copy.(因此@tiziano 的回答具有误导性).

>>>打印\c"\C

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

I have a python module which copy data from a table to a file.Im using postgresql as database server. COPY is the command is to be used to do the above action.

However in a blog (grokbase/t/postgresql/pgsql-general/058tagtped/about-error-must-be-superuser-to-copy-to-or-from-a-file) it states that, You can use \copy in 'psql' on the client side, but you have to be a superuser to do COPY on the server side, for security reasons. So I used \copy command. When I try to execute the below method, it results in error as

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

I can't find why its throwing error. can someone help me out?

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.

解决方案

\ is an escape in Python strings, so your string contains the escape \c. However \c is an invalid escape in Python, and Python leaves invalid escapes unchanged, so "\copy" is just \copy. (Thus @tiziano's answer is misleading).

>>> print "\c" \c

The real problem is that \copy is a psql command, not a server side PostgreSQL command. You can't use it with a client other than psql. You must instead use the psycopg2 support for COPY to do it via your client driver.

更多推荐

psycopg2.ProgrammingError:“\"处或附近的语法错误;

本文发布于:2023-10-14 21:59:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492334.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法错误   ProgrammingError   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!