psycopg2: DictCursor vs RealDictCursor

时间秒杀一切 提交于 2020-03-21 11:55:07

问题


AFAIU and from docs, RealDictCursor is a specialized DictCursor that enables to access columns only from keys (aka columns name), whereas DictCursor enables to access data both from keys or index number.
I was wondering why RealDictCursor has been implemented if DictCursor offers more flexibility? Is it performance-wise (or memory-wise) so different (in favor of RealDictCursor I imagine...)?
In other words, what are RealDictCursor use cases vs DictCursor?


回答1:


The main advantage of real dictionary cursor is the easiness to get a query output as json.

Compare:

with psycopg2.connect('dbname=test') as connection:
    with connection.cursor(cursor_factory=RealDictCursor) as cursor:
        cursor.execute("select * from my_table")
        print(json.dumps(cursor.fetchall()))

versus

with psycopg2.connect('dbname=test') as connection:
    with connection.cursor() as cursor:
        cursor.execute("select * from my_table")
        columns = [desc[0] for desc in cursor.description]
        real_dict = [dict(zip(columns, row)) for row in cursor.fetchall()]
        print(json.dumps(real_dict))

There is no important difference between these options when it comes to performance.

You cannot get an expected json using json.dumps(cursor.fetchall()) for regular or dictionary-like cursors and need the conversion showed above. On the other hand, real dictionary cursor produces a much larger result so you should not use it if you really do not need it.




回答2:


class psycopg2.extras.RealDictCursor(*args, **kwargs)

A cursor that uses a real dict as the base type for rows. Note that this cursor is extremely specialized and does not allow the normal access (using integer indices) to fetched data. If you need to access database rows both as a dictionary and a list, then use the generic DictCursor instead of RealDictCursor. class psycopg2.extras.RealDictConnection A connection that uses RealDictCursor automatically.

Note Not very useful since Psycopg2.5: you can use psycopg2.connect(dsn, cursor_factory=RealDictCursor) instead of RealDictConnection. class psycopg2.extras.RealDictRow(cursor) A dict subclass representing a data record.




来源:https://stackoverflow.com/questions/45399347/psycopg2-dictcursor-vs-realdictcursor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!