无法使用psycopg2从postgre数据库中提取数据

时间:2014-05-09 17:41:46

标签: python postgresql

我对python PostgreSQL有问题。我正在使用psycopg2。 这是我的postgres DB看起来像:

Database: qcdata
    ---information_schema
    ---pg_catalog
    ---prod
        ---activation
        --- *** Many other table ***
    ---public

我想提取架构中的信息:prod - table:activation

这是我的代码

import psycopg2
conn = psycopg2.connect(host='10.0.80.180', port = '5432',
                    dbname = 'qcdata', 
                    user = 'username', password = 'pwd')
cur = conn.cursor()
print cur.execute("SELECT * FROM prod.activation")

但是它返回None ...我确信它中有数据。怎么会这样? 谢谢你们。

2 个答案:

答案 0 :(得分:2)

根据文档(http://initd.org/psycopg/docs/cursor.html),cur.execute()游标始终返回None。您必须使用其中一种获取方法,例如:

print cur.fetchall()

-g

答案 1 :(得分:0)

虽然我会在我获得单个值的情况下使用cursor.fetchone(),但在使用COUNT时:

SELECT count(*) FROM prod.activation

如果我想处理一组行,我想利用光标在结果集上iterate的能力。这样可以更好地控制结果,如何处理结果以及如何返回结果。

可以像Python列表一样迭代游标:

for row in cur:
    dostuff()

如果你使用named cursors(只需在构造游标时设置name属性),psycopg2将为你SELECT组块,默认为2000。这将在迭代时自动在后台发生。

您也可以使用with语法在完成光标后自动关闭光标。 (适用于较小范围的用途。)