psycopg 和 python3:投射检索到的数据

psycopg and python3: casting retrieved data

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

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 列需要放在括号外。