How to preserve column order while using psycopg2.extras.RealDictCursor

dict_cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
dict_cur.execute("SELECT column1, column2, column3 FROM mytable")
result = dict_cur.fetchall()
print result[0]
>>> {'column2':10, 'column1':12, 'column3':42}

How could I preserve column ordering without parsing executed SQL first? It works well with normal cursor when list is returned, but I need access to dictionary keys and therefore need to use RealDictCursor.

EDIT : Well, I actually can't. description attribute of the cursor object should be used for getting column names.


You can use psycopg2.extras.NamedTupleCursor and then use namedtuple_obj._asdict() to convert that to an OrderedDict .

Note: In ordered to get this functionality "out of the box" we need to have Python version >= 2.7.


I don't have this " extras " package, but normally a cursor should have a property called description which is a tuple containing all the columns in order along with some additional information like field type etc.

Try out " print dict_cur.description " in a python shell and see what you get.

EDIT: never mind. I did not read your "EDIT"...

链接地址: http://www.djcxy.com/p/10452.html

上一篇: Yii CDBCommand getText在SQL中显示所有变量

下一篇: 如何在使用psycopg2.extras.RealDictCursor时保留列顺序