我使用的是Python2.7和postgresql 9.1。 试图从查询中获取字典,我尝试了下面描述的代码: http://wiki.postgresql.org/wiki/Using_psycopg2_with_PostgreSQL
import psycopg2
import psycopg2.extras
conn = psycopg2.connect("dbname=mydb host=localhost user=user password=password")
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute ("select * from port")
type(cur.fetchall())
它正在打印下一个答案:
<type 'list'>
打印项目本身,显示它是列表。 例外的答案是字典。
编辑:
尝试下一个:
ans = cur.fetchall()[0]
print ans
print type(ans)
回报
[288, 'T', 51, 1, 1, '192.168.39.188']
<type 'list'>
也许我们可以进一步优化它
这很正常:当您调用
.fetchall()
时,方法返回元组列表。但如果你写信它将只返回一个类型为的元组:
在此之后,您可以将其用作列表或类似字典:
您还可以使用一个简单的游标迭代器:
Tnx很多Andrey Shokhin
完整的答案是:
相关问题 更多 >
编程相关推荐