我需要在 PostgreSQL 中运行查询以首先更新记录,然后返回它。这是查询:
WITH x AS (
SELECT "ID" FROM JOB WHERE "STATE" = 1 LIMIT 1
)
UPDATE JOB y SET "STATE" = 2 FROM x WHERE x."ID" = y."ID"
RETURNING y.*
它在 PostgreSQL 服务器本身运行良好。但是,在 Python 中使用 pyodbc 运行它不起作用。
cursor.execute(query)
results = cursor.fetchall()
它说“没有结果。之前的 SQL 不是查询。”
此评论更像是注释而不是直接答案,因为我正在使用另一个库,但是
psycopg2
与 returning
语句完美配合:
conn = psycopg2.connect(url)
cursor = conn.cursor()
query = '''
WITH x AS (
SELECT "id", apples FROM bucket WHERE "id" = 10
)
UPDATE bucket y SET apples = y.apples + 1 FROM x WHERE x."id" = y."id"
RETURNING y.*;
'''
cursor.execute(query, [])
cursor.commit()
result = cursor.fetchone()
print('------>\n', result)
将打印带有
id = 10
的行值的列表。