python 3.X - psycopg和python3:转换检索到的数据



我遇到Python3.4和psycopg2的问题。我可以成功地强制转换选择所有内容或单个列的语句,但不能强制转换针对特定列的语句,例如:

import psycopg2, psycopg2.extras

conn = psycopg2.connect(...)
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
''' This works! '''
cursor.execute("""SELECT * FROM table;""")
row = cursor.fetchone()
print( row['colname'] )

''' This doesn't: it returns a KeyError'''
cursor.execute("""SELECT (colname, other_col) FROM table;""")
row = cursor.fetchone()
print ( row['colname'] )

''' This works'''
cursor.execute("""SELECT (colname) FROM table;""")
row = cursor.fetchone()
print(row['colname'])

''' This works: it returns lists instead of dicts, accessing by row[key] rises an error, accessing by row[int] doesn't '''
cursor.execute("""SELECT * FROM table;""")
allrows = cursor.fetchall()
print ( allrows[0][1] )

''' This doesn't work: it returns rows as lists of form ['(val1, val2)']'''
cursor.execute("""SELECT (colname, other_col) FROM table;""")
allrows = cursor.fetchall()
print ( allrows[0][1] )

有没有人知道为什么会发生这种情况,以及我如何获得语句,如SELECT (colname, other_col)的工作?

嗯,这似乎是一个简单的错别字:SELECT列需要在括号之外

最新更新