我试图使用 psycopg2
与我的postgresql数据库只是在我的本地机器上运行无法让它返回结果无论我尝试什么 . 它似乎连接到数据库确定,因为如果我改变任何配置参数它会抛出错误,但是,当我运行看似有效和结果有 Value 的查询时,我什么也得不到 .
我的数据库正在运行,并且肯定有一个表:
postgres=# \c
You are now connected to database "postgres" as user "postgres".
postgres=# select * from foos;
name | age
---------+-----
Sarah | 23
Michael | 35
Alice | 12
James | 20
John | 52
(5 rows)
我的python代码连接到这个数据库,但不管我运行什么查询,我得到 None
:
Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import psycopg2
>>> conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost'")
>>> cur = conn.cursor()
>>> print cur.execute("select * from foos;")
None
>>> print cur.execute("select * from foos")
None
>>> print cur.execute("select name from foos")
None
>>> print cur.execute("select f.name from foos f")
None
我做错了什么吗?我怎么能开始调试这个,我不知道从哪里开始,因为它连接得很好?
4 回答
cursor.execute
准备并执行查询但不获取任何数据,因此None
是预期的返回类型 . 如果要检索查询结果,则必须使用fetch*
方法之一:请注意,正如文档中所述:http://initd.org/psycopg/docs/cursor.html "cursor objects are iterable, so, instead of calling explicitly fetchone() in a loop, the object itself can be used"
因此,编写它同样有效:
没有显式调用fetchone() . 我们pythonistas应该更喜欢简洁的代码,只要它不会损害理解,并且imho,这感觉更自然 .
游标的
execute()
方法只执行传递给它的SQL . 然后,您有几个选项可以从光标获取响应 . 您可以使用fetchone()
方法返回下一个结果 . 在第一次调用它时,您将获得第一个结果,第二次获得第二个结果,依此类推 .fetchall()
方法返回 all 行,可以用作迭代器 .例子:
您没有阅读具有完美示例的基本文档
http://initd.org/psycopg/docs/cursor.html