psycopg2在“UPDATE”处或附近出现语法错误

2024-04-26 10:26:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我读过一些关于“语法错误在或附近”的问答,但没有一个能解决我的问题。在

错误示例:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
psycopg2.ProgrammingError: syntax error at or near "UPDATE"
LINE 1: DECLARE "teste" CURSOR WITHOUT HOLD FOR UPDATE applicant SET...
                                                ^

请注意UPDATE右边的^。我已经在pgadmin 4上测试了更新脚本,一切正常。在

脚本非常简单:

^{pr2}$

我的代码基本上是:

def _connect_database():
    return psy.connect(
        dbname=settings.DATABASE['DBNAME'],
        host=settings.DATABASE['HOST'],
        port=settings.DATABASE['PORT'],
        user=settings.DATABASE['USER'],
        password=settings.DATABASE['PASSWORD'],
        application_name=settings.env
    )

# Connects to database
conn = _connect_database()
# Creats a named cursor
cur = conn.cursor('test')

# Execute
cur.execute(update_script, ('{"json": "test"}', '00025ba0-748f-11e8-b0d3-d7108dd3af23'))

我已经在execute方法和参数上显式地编写了脚本,但仍然得到相同的错误:

cur.execute("UPDATE applicant SET cv_recrutai_entities = 'json here' WHERE id = '00025ba0-748f-11e8-b0d3-d7108dd3af23'")

注意,我甚至删除了第一个参数('json here')中的双引号

我错过什么了吗?!在


Tags: test脚本jsonexecutesettingsconnect错误update
1条回答
网友
1楼 · 发布于 2024-04-26 10:26:23

cur = conn.cursor('test')

您正试图打开服务器端游标。Per the documentation:

cursor(name=None, cursor_factory=None, scrollable=None, withhold=False)

Return a new cursor object using the connection.

If name is specified, the returned cursor will be a server side cursor (also known as named cursor). Otherwise it will be a regular client side cursor.

只使用

^{pr2}$

服务器端(命名)游标只能用于SELECT或VALUES查询。它们实现了Postgres cursors:

query

A SELECT or VALUES command which will provide the rows to be returned by the cursor.

使用命名游标,结果数据在服务器上收集,并在需要时(可能是部分地)发送到客户机(获取)。数据只在打开光标的事务期间存储,因此commit或{}释放它。在

客户端(未命名)游标允许执行任何有效的SQL查询。可能的结果集在执行查询后立即发送到客户端。在

使用一个连接可以使用命名和未命名的游标,但是如果您想同时执行此操作,则应该使用两个单独的连接。在

相关问题 更多 >