【发布时间】:2015-08-11 04:47:12
【问题描述】:
我正在尝试在 psycop2 中使用服务器端光标,详见 this blog post。本质上,这是通过
from django.db import connection
if connection.connection is None:
cursor = connection.cursor()
# This is required to populate the connection object properly
cursor = connection.connection.cursor(name='gigantic_cursor')
当我执行查询时:
cursor.execute('SELECT * FROM %s WHERE foreign_id=%s' % (table_name, id))
我收到ProgrammingError:
psycopg2.ProgrammingError: can't use a named cursor outside of transactions
我天真地尝试使用
创建交易cursor.execute('BEGIN')
在执行SELECT 语句之前。但是,这会导致 cursor.execute('BEGIN') 行产生相同的错误。
我也试过
cursor.execute('OPEN gigantic_cursor FOR SELECT * FROM %s WHERE foreign_id=%s' % (table_name, id))
但我得到了相同的结果。
如何在 django 中进行交易?
【问题讨论】:
-
从错误消息看来,您的光标在事务之外。尝试在事务中使用游标。
-
请参阅this answer,了解如何设置它的示例。
标签: django postgresql transactions psycopg2