Psycopg2. Change cursor factory for a single query

Viewed 67

I'm using RealDictRow cursor as default cursor. But For some specific queries regular (tuple) cursor is more handy. Is psycopg2 allows to replace cursor during a single query?

Usage example:

cursor.execute('SELECT id FROM posts', cursor_factory=None)
# Not working, unexpected argument
1 Answers

You can't change the type of an existing cursor, but you can override the connection's cursor_factory when declaring a new cursor:

>>> # Declare a connection that produces DictCursors by default. 
>>> conn = psycopg2.connect(dbname='test', cursor_factory=psycopg2.extras.DictCursor)
>>> cur1 = conn.cursor()
>>> type(cur1)
<class 'psycopg2.extras.DictCursor'>
>>>
>>> # Create a standard cursor by overriding cursor_factory.
>>> cur2 = conn.cursor(cursor_factory=psycopg2.extensions.cursor)
>>> type(cur2)
<class 'psycopg2.extensions.cursor'>
Related