首页 文章

psycopg2没有返回结果

提问于
浏览
13

我试图使用 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 回答

  • 17

    cursor.execute 准备并执行查询但不获取任何数据,因此 None 是预期的返回类型 . 如果要检索查询结果,则必须使用 fetch* 方法之一:

    print cur.fetchone()
    
    rows_to_fetch = 3
    print cur.fetchmany(rows_to_fetch)
    
    print cur.fetchall()
    
  • 1

    请注意,正如文档中所述: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"

    因此,编写它同样有效:

    >>> cur.execute("select foo, bar from foobars")
    >>> for foo, bar in cur:
    ....    print foo, bar
    

    没有显式调用fetchone() . 我们pythonistas应该更喜欢简洁的代码,只要它不会损害理解,并且imho,这感觉更自然 .

  • 5

    游标的 execute() 方法只执行传递给它的SQL . 然后,您有几个选项可以从光标获取响应 . 您可以使用 fetchone() 方法返回下一个结果 . 在第一次调用它时,您将获得第一个结果,第二次获得第二个结果,依此类推 . fetchall() 方法返回 all 行,可以用作迭代器 .

    例子:

    >>> # This is an example of the fetchone() method
    >>> cur.execute("select * from foos")
    >>> # This call will return the first row 
    >>> result = cur.fetchone()
    >>> # This call will return the second row
    >>> result = cur.fetchone()
    
    
    >>> # This is an example of the fetchall() method
    >>> cur.execute("select * from foos")
    >>> results = cur.fetchall()
    >>> for r in results:
    ...     print r
    >>> # Now we'll reset the cursor by re-executing the query
    >>> cur.execute("select * from foos")
    >>> for r in cur.fetchall():
    ...     print r
    
  • 3

    您没有阅读具有完美示例的基本文档

    http://initd.org/psycopg/docs/cursor.html

    >>> cur.execute("SELECT * FROM test WHERE id = %s", (3,))
    >>> cur.fetchone()
    (3, 42, 'bar')
    

相关问题