1

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
salius
  • 918
  • 1
  • 14
  • 30

1 Answers1

0

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'>
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153